Reputation: 3721
The idea is to take one single file, but I don't want to list all of the files. I have the address of the specified folder, but not the name.
Basically I want
findFileInFolder(String folderName) --- this method returns a random filename or the oldest file created on the folder
Has anybody ever tried doing this? Any ideas to avoid listing all of the files in an array and then taking the first one?
Added:
Just in case I wasn't clear (I'm really sorry for my English. Please forgive me if I sound prepotent or aggressive it is really not my intentions.) The file is not selected by a human, it's selected by the machine without asking or showing the file except for the method that returns a string with the FileName
String findFileInFolder(String folderName)
Like I comment is for usage of ram and processor because this is a secondary process and not the primary of the project, so if I have to read over a thousand files it will considerably reduce the performance of my project :(
Thanks ;)
Update: the program is running on different computers so if I could just access the directory not "thinking" about reading which file it would be great. =D
Hopefully last update: sorry for bothering you guys :)
From what I read on the answers there is no way. My question is: what good alternatives instead of doing an array would you think? My idea is to create an index in a textfile and to take only the first line.
Upvotes: 4
Views: 15939
Reputation: 1
I realize this is an old thread but here is a quick and dirty way to do it:
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
public class Shuffle {
public static void main(String[] argv)
throws Exception {
File dir = new File(".");
String[] children = dir.list();
Collections.shuffle(Arrays.asList(children));
System.out.println(children[0]);
}
}
Upvotes: -1
Reputation: 3721
I decidee to use this code, is not exactly what I wanted but it works for now.
public static String getFileToCrawl(String directory){
File dir = new File(directory);
String[] children = dir.list();
if (children == null) {
return "";
} else {
int i=0;
String filename = children[i];
while (i<children.length && !filename.contains(".txt")){
i++;
filename = children[i];
}
return filename;
}
}
if anyone like it or know a way to improve this code it's really welcome ;) if you want to use it feel free :D
Upvotes: 2
Reputation: 19177
There is no way of doing this in current versions of java other than listing all files and selecting what you need. If you can use java 7, there is a FileVisitor class that can walk a folder tree without listing all of the files.
Upvotes: 0
Reputation: 19060
You can have a look on FileFilter
class and on the public File[] listFiles(FileFilter filter)
Using this method you will be able to filter files according to their last modification date for example.
On a side note, why do you want to avoid to list all the files, for performances concerns ?
Upvotes: 1