How are files from a directory specified in Java?
I have a directory from which I need to read txt files.
Here is the code:
try {
File dir = new File(directoryName);
File[] files = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
});
for (File xmlfile : files) {
System.out.println("File name:" + xmlfile.getAbsolutePath());
}
} catch (Exception e) {
System.out.println(e);
}
A test case was created:
1. A directory named "content" was created. It was filled with two files: 1.txt and 2.txt. They were created in the same order in which they were mentioned.
2. One of the files, 1.txt has been renamed to sriram.txt (say).
Here are the results I got:
1. On Windows, files were always listed in alphabetical order.
2. In Linux, files were listed by timestamp. On Ubuntu, files were listed in reverse order of timestamps. On other distributions on Debian, files were listed in ascending order of time.
My question (s):
1. How does Java internally work to list files? The documentation for listFiles
and FilenameFilter
is unclear. 2. From the above test case, you can see that there is something OS-specific that Java picks up when writing files. What is it and how to display it?
source to share
The documentation is absolutely clear:
There is no guarantee that the name strings in the resulting array will appear in any particular order; they, in particular, are not guaranteed in alphabetical order.
(Most of the time, when you want the filenames to appear in a given order, you also need to implement other orders, so you don't really waste a lot by always sorting the list manually.)
source to share