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 thus:
1. A directory named "content" was created. It was populated with two files: 1.txt and 2.txt. These were created in the same order as they have been mentioned.
2. One of the files, 1.txt was renamed to sriram.txt (say).
Here are the results I got:
1. On Windows, the files were always listed alphabetically.
2. On Linux, the files were listed by timestamp. On Ubuntu, the files were listed in reverse order of the timestamps. On other Debian-based distros, the files were listed in ascending order of timestamp.
My question(s):
1. How does Java work internally to list the files? The documentation for listFiles and FilenameFilter are not clear on this.
2. It seems, from the above test case, that there is something OS-specific that Java is picking up on when listing files. What is this and how do I display it?
The documentation is absolutely clear on this:
There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order.
(In most cases when you need file names to appear in a given order, you generally need to implement other orders too, so actually you aren't losing much by having to always sort the list manually.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With