how do you search for something in an array in java - java

I wan to create a public, non-static method that does this:
getContent : This method should take as input a String filename and return a String. The method should search for a file with name filename in the array drive and return the data that is stored in that TxtFile. If no such file exists in the array drive, the method should return null.
I don't know how to search for something in an array. can someone show me how to do this?

Come on, try it your self:
Step1: Read all the file Names from a directory.
Step2: Store the list of Files to a List.
Step3: Iterate the list, Write a conditions with a use the File.getName() method to compare and the name and your input.
if(file.getName().equals(inputFileName)){
return "boooo! I have found You!"
}

You search in an array by iterating of it. Something like this (if you are inside a method):
for(String x : someStringArray){
if (somecondition(x)) return x;
}

this should be of help: File search
A definitive source for information.
EDIT: thought of something really simple:
String[] drives = new String[]{"C:\\", "D:\\"};
File file;
for(String drive : drives)
{
file = new File(drive + "abc.txt");
JOptionPane.showMessageDialog(null, file.exists());
}
you can replace the showMessageDialogBox with whatever you want to do if the file exists.

Related

Adding files from folder to the list in android app

I'm trying to create a list of files in my sdcard (and then get a random one from this list).
I've read tutorials but none of those worked.
My code is as following:
try{
File file=new File("/sdcard");
File[] list = new File ("/sdcard").listFiles();
ArrayList<String> lista = new ArrayList<String>();
for (File f : list){
if (f.isFile()){
if (f.getName().startsWith("aa")){
lista.add(f.getName());
}
}
}
Random gen = new Random();
String s = lista.get(gen.nextInt(lista.size()-1)).toString();
wyswietl.setText(s);
}catch(NullPointerException e){
Log.e("nope", e.getMessage());
}
LogCat shows exceptions.
I've checked every single line - when I try to show lista.size() - it throws ResourcesNotFoundException.
What interesting is, changing String s into
String s = lista.get(1).toString()
works - it shows me one of the files in the folder.
So my question is: how can I fix this and get a list of files (which start with "aa") in /sdcard folder?
If you want to pick one random item in array list, I believe it should be
String s = lista.get(gen.nextInt(lista.size()));
Random.nextInt(int n) retrieves random value between 0-(n-1). See Random.nextInt() documentation.
ResourceNotFound exception I believe is related to failure to locate resource ID inside R.java not index out of bound exception.
TextView.setText() with integer value parameter, interprets integer value as a resource ID, see here. So if you call
atextView.setText(lista.size());
It will throw ResourceNotFoundException because it may not point to correct resource ID. If you want to display number of items in list then
atextView.setText(String.valueOf(lista.size()));
If lista.size () equals 0 then exception can occur...
( because gen.nextInt (-1) )
I hope you to prevent it.
Here is the different way to the filter on list of file based on file name !!!!
File f = new File("/sdcard");
String fileList[];
if(f.isDirectory()){
fileList = f.list(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
// TODO Auto-generated method stub
if (name.startsWith("aa")){
return true;
}
return false;
}
});
'FileList' is an array where you get all the File object and then you can easily get the file name from that!!!!
Hope this will help!!!
I've found the solution why this code didn't work. The files weren't in the folder yet - i had to add names to the list manually, then in other function check if they are on sdcard (if not, there is need to copy; if yes, I can display the content).

Searching files in a directory and pairing them based on a common sub-string

I have been attempting to program a solution for ImageJ to process my images.
I understand how to get a directory, run commands on it, etc etc. However I've run into a situation where I now need to start using some type of search function in order to pair two images together in a directory full of image pairs.
I'm hoping that you guys can confirm I am on the right direction and that my idea is right. So far it is proving difficult for me to understand as I have less than even a month's worth of experience with Java. Being that this project is directly for my research I really do have plenty of drive to get it done I just need some direction in what functions are useful to me.
I initially thought of using regex but I saw that when you start processing a lot of images (especially with imagej which it seems does not dump data usage well, if that's the correct way to say it) that regex is very slow.
The general format of these images is:
someString_DAPI_0001.tif
someString_GFP_0001.tif
someString_DAPI_0002.tif
someString_GFP_0002.tif
someString_DAPI_0003.tif
someString_GFP_0003.tif
They are in alphabetical order so it should be able to go to the next image in the list. I'm just a bit lost on what functions I should use to accomplish this but I think my overall while structure is correct. Thanks to some help from Java forums. However I'm still stuck on where to go to next.
So far here is my code: Thanks to this SO answer for partial code
int count = 0;
getFile("C:\");
string DAPI;
string GFP;
private void getFile(String dirPath) {
File f = new File(dirPath);
File[] files = f.listFiles();
while (files.length > 0) {
if (/* File name contains "DAPI"*/){
DAPI = File f;
string substitute to get 'GFP' filename
store GFP file name into variable
do something(DAPI, GFP);
}
advance to next filename in list
}
}
As of right now I don't really know how to search for a string within a string. I've seen regex capture groups, and other solutions but I do not know the "best" one for processing hundreds of images.
I also have no clue what function would be used to substitute substrings.
I'd much appreciate it if you guys could point me towards the functions best for this case. I like to figure out how to make it on my own I just need help getting to the right information. Also want to make sure I am not making major logic mistakes here.
It doesn't seem like you need regex if your file names follow the simple pattern that you mentioned. You can simply iterate over the files and filter based on whether the filename contains DAPI e.g. see below. This code may be oversimplification of your requirements but I couldn't tell that based on the details you've provided.
import java.io.*;
public class Temp {
int count = 0;
private void getFile(String dirPath) {
File f = new File(dirPath);
File[] files = f.listFiles();
if (files != null) {
for (File file : files) {
if (file.getName().contains("DAPI")) {
String dapiFile = file.getName();
String gfpFile = dapiFile.replace("DAPI", "GFP");
doSomething(dapiFile, gfpFile);
}
}
}
}
//Do Something does nothing right now, expand on it.
private void doSomething(String dapiFile, String gfpFile) {
System.out.println(new File(dapiFile).getAbsolutePath());
System.out.println(new File(gfpFile).getAbsolutePath());
}
public static void main(String[] args) {
Temp app = new Temp();
app.getFile("C:\\tmp\\");
}
}
NOTE: As per Vogel612's answer, if you have Java 8 and like a functional solution you can have:
private void getFile(String dirPath) {
try {
Files.find(Paths.get(dirPath), 1, (path, basicFileAttributes) -> (path.toFile().getName().contains("DAPI"))).forEach(
dapiPath -> {
Path gfpPath = dapiPath.resolveSibling(dapiPath.getFileName().toString().replace("DAPI", "GFP"));
doSomething(dapiPath, gfpPath);
});
} catch (IOException e) {
e.printStackTrace();
}
}
//Dummy method does nothing yet.
private void doSomething(Path dapiPath, Path gfpPath) {
System.out.println(dapiPath.toAbsolutePath().toString());
System.out.println(gfpPath.toAbsolutePath().toString());
}
Using java.io.File is the wrong way to approach this problem. What you're looking for is a Stream-based solution using Files.find that would look something like this:
Files.find(dirPath, 1, (path, attributes) -> {
return path.getFileName().toString().contains("DAPI");
}).forEach(path -> {
Path gfpFile = path.resolveSibling(/*build GFP name*/);
doSomething(path, gfpFile);
});
What this does is:
Iterate over all Paths below dirPath 1 level deep (may be adjusted)
Check that the File's name contains "DAPI"
Use these files to find the relevant "GFP"-File
give them to doSomething
This is preferrable to the files solution because of multiple things:
It's significantly more informative when failing
It's cleaner and more terse than your File-Based solution and doesn't have to check for null
It's forward compatible, and thus preferrable over a File-Based solution
Files.find is available from Java 8 onwards

JSON to Export .txt Order in Java

I have this code, and the string is coming from JSON from the server, and I use these if statements to prioritize what I want to get exported to the text file, but when I run it, the output isnt the output I am expecting, see below:
JSONObject attributeObject = objects.getJSONObject(objectAttribute);
String[] elementList = JSONObject.getNames(attributeObject);
for (String attributeName : elementList) {
if (attribute.equals("Custodian")){
String value = objects.getString("attributeValue");
System.out.print(value+",");
out.write(value);
out.append(",");
}
if (attribute.equals("Custodian Delegate")){
String value = objects.getString("attributeValue");
System.out.print(value+",");
out.write(value);
out.append(",");
}
if (attribute.equals("Authentication Directory")){
String value = objects.getString("attributeValue");
System.out.print(value+",");
out.write(value);
out.append(",");
}
if (attribute.equals("User ID")){
String value = objects.getString("attributeValue");
System.out.println(value);
out.write(value);
out.append(",");
out.newLine();
}
}
Expected output based from the if statements:
JDoe,CPer,Active Directory, No
But once I run it, the output becomes:
Active Directory,JDoe,CPer,No
Is there an easier way to fix this? My only problem is that the Authentication Directory goes first when I start running the program. Any tips? I would greatly appreciate.
Thanks in advance
make your life easy by creating a Model class
class Model{
String JDoe=""; //this is an example, so change attribute names using naming convention
String CPer="";
String Active_Directory="";
String No="";
#Override
public String toString(){
return JDoe+", " +CPer+", " +Active_Directory+", " + No;
}
}
now change your code to use this model, and only update the class Model without writing anything to the file.
for example:
Model model = new Model();
...
for(whatever condition is){ //start of the loop
if (attribute.equals("Custodian")){
String value = objects.getString("attributeValue");
model.CPer=value;
//System.out.print(value+",");
//out.write(value); <-- skip this
//out.append(","); <-- skip this
}
...
}
//after the loop
out.write(model.toString());
NOTE:
if you have two loops place Model model = new Model();
inside your outter loop
The output might be correct. You are iterating over all keys of the JSON-object. The resulting order does not depend on the order of your if-satements. In every loop only a single if-condition matches. The given snippet will output the elements in the same order as in the returned array.
The .getNames() returnes the array of the field names of the given Object. Then you are iterating over theses field names. Therfore the attribute value will have the same value per cycle. It is impossible that two if-condition will match because attribute can not equal for example "Custodian" and "Custodian Delegate" at thes same time.
It seems like the array contains the attributes in an alphabetic order. Therefore the attributeName-variable is "Authentication Directory" during the first cycle.

How to create a new Section in the dataprovider ini4j

I am reading from ini files and passing them via data providers to test cases.
(The data provider reads these and returns an Ini.Section[][] array. If there are several sections, testng runs the test that many times.)
Let's imagine there is a section like this:
[sectionx]
key1=111
key2=222
key3=aaa,bbb,ccc
What I want, in the end, is to read this data and execute the test case three times, each time with a different value of key3, the other keys being the same.
One way would be to copy&paste the section as many times as needed... which is clearly not an ideal solution.
The way to go about it would seem to create further copies of the section, then change the key values to aaa, bbb and ccc. The data provider would return the new array and testng would do the rest.
However, I cannot seem to be able to create a new instance of the section object. Ini.Section is actually an interface; the implementing class org.ini4j.BasicProfileSection is not visible. It does not appear to be possible to create a copy of the object, or to inherit the class. I can only manipulate existing objects of this type, but not create new ones. Is there any way around it?
It seems that it is not possible to create copies of sections or the ini files. I ended up using this workaround:
First create an 'empty' ini file, that will serve as a sort of a placeholder. It will look like this:
[env]
test1=1
test2=2
test3=3
[1]
[2]
[3]
...with a sufficiently large number of sections, equal or greater to the number of sections in the other ini files.
Second, read the data in the data provider. When there is a key that contains several values, create a new Ini object for each value. The new Ini object must be created from a new file object. (You can read the placeholder file over and over, creating any number of Ini files.)
Finally, you have to copy the content of the actual ini file into the placeholder file.
The following code code works for me:
public static Ini copyIniFile(Ini originalFile){
Set<Entry<String, Section>> entries = originalFile.entrySet();
Ini emptyFile;
try {
FileInputStream file = new FileInputStream(new File(EMPTY_DATA_FILE_NAME));
emptyFile = new Ini(file);
file.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
for(Entry<String, Section> entry : entries){
String key = (String) entry.getKey();
Section section = (Section) entry.getValue();
copySection(key, section, emptyFile);
}
return emptyFile;
}
public static Ini.Section copySection(String key, Ini.Section origin, Ini destinationFile){
Ini.Section newSection = destinationFile.get(key);
if(newSection==null) throw new IllegalArgumentException();
for(Entry<String, String> entry : origin.entrySet()){
newSection.put(entry.getKey().toString(), entry.getValue().toString());
}
return newSection;
}

What should be the description for this method?

OK this method reads a dirctor, verify the file paths are ok and then pass each file to a method and updates a Map object.
But how can i explain this for java doc. I want to create a java doc and how should i explain this method for the documentation purpose. Please tell me, if you can help me with this example, i can work for my whole project. thank you:
private void chckDir() {
File[] files = Dir.listFiles();
if (files == null) {
System.out.println("Error");
break;
}
for (int i = 0; i < files.length; i++) {
File file = new File(files[i].getAbsoluteFile().toString());
Map = getMap(file);
}
}
Your method doesn't do what you said In your first sentence (doesn't verify file paths, and throws the result of getMap() away), but there's nothing wrong with putting that kind of sentence im the Javadoc.
There are some issues with your code:
The break statement will give a compilation error, I think. It should be a return.
It is bad style to name a field with a capital letter as the first character. If Dir and Map are field names, they should be dir and map respectively.
The statement Map = getMap(file); is going to repeatedly replace the Map field, and when you exit the loop, the field will refer to the object returned by the last getmap call. This is probably wrong.
Finally, change the file declaration as follows. (There is no need to create a new File object ... because getAbsoluteFile() reurns a File)
File file = files[i].getAbsoluteFile();

Categories