I'm writing a code where in there a bunch of files that have to be taken as input from a directory.
The program works fine, but the problem comes up in the way the files are picked. In my directory when I do a sort the first file shown is file5521.3
, but in my program the first file that is picked up is file5521.100
. THis is pretty confusing.
I've also tried using Arrays.sort(list, NameFileComparator.NAME_COMPARATOR)
, but it also gives the same result as previous.
Below is my code.
void countFilesInDirectory(File directory, String inputPath) throws IOException {
File[] list = directory.listFiles();
Arrays.sort(list, NameFileComparator.NAME_COMPARATOR);
for (int i = 0; i < list.length; i++) {
System.out.println(list[i]);
}
tempPath = inputPath.substring(0, inputPath.lastIndexOf("\\") + 1) + "OP\\";
File outPath = new File(tempPath);
if (!outPath.exists()) {
outPath.mkdir();
}
File temp = new File(tempPath + "temp.txt");
FileOutputStream fos = new FileOutputStream(temp);
if (!temp.exists()) {
temp.createNewFile();
}
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
for (int i = 0; i < list.length; i++) {
System.out.println(list[i]);
setStatusText(i);
GenerateFiles(list[i].getAbsoluteFile().toString(), bw);
}
bw.write("</body>");
bw.close();
File newFile = new File(temp.getParent(), "Index.html");
Files.move(temp.toPath(), newFile.toPath());
}
please let me know how can I do this.
Working Solution with Last Modified Date
Arrays.sort(list, new Comparator<File>() {
public int compare(File f1, File f2) {
return Long.compare(f1.lastModified(), f2.lastModified());
}
});
The Comparator
works fine with last modified date, but when I try it with below code. The result is same as previous.
Arrays.sort(list, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
return o1.getName().compareTo(o2.getName());
}
});
In my Windows Explorer It looks like below. I've sorted the filenames.
And my console output shows the below.
Thanks