I've wrote a little Webserver app. Now I have the problem, that I don't now how i can display index files. How can I get the first file in directory which starts with index? No matter which file extension. I get the dir with new File("Path/To/Dir");
.
Please help me!
Greetings
You could use the File#list()
method.
// your directory in which you look for index* files
File directory = new File(".");
// note that indexFileNames may be null
String[] indexFileNames = directory.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("index");
}
});
if (indexFileNames != null) {
for (String name : indexFileNames) {
System.out.println(name);
}
}
This will find all files which names start with index
prefix.
Please note that list()
method returns names of both files and directories. If you only need files, you can augment the FilenameFilter
logic.
To get the first of these files, you need to define some order. For example, if you need to sort files on their names alfabetically (in case-sensitive manner), you could do the following:
if (indexFileNames != null) {
// sorting the array first
Arrays.sort(indexFileNames);
// picking the first of them
if (indexFileNames.length > 0) {
String firstFileName = indexFileNames[0];
// ... do something with it
}
}
You could also sort with some comparator if you need some special order:
Arrays.sort(indexFileNames, comparator);
Yet another way is to avoid sorting and use Collections#min()
method:
if (indexFileNames.length > 0) {
String firstFileName = Collections.min(Arrays.asList(indexFileNames));
// ... process it
}
Collections#min()
also has a version with Comparator
.