【发布时间】:2016-04-01 15:12:52
【问题描述】:
我正在编写一个代码,其中有一堆文件必须作为目录的输入。
程序运行良好,但问题出现在文件的选取方式上。在我的目录中,当我进行排序时,显示的第一个文件是file5521.3,但在我的程序中,选择的第一个文件是file5521.100。这很令人困惑。
我也尝试过使用Arrays.sort(list, NameFileComparator.NAME_COMPARATOR),但它也给出了与之前相同的结果。
下面是我的代码。
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());
}
请告诉我该怎么做。
具有上次修改日期的工作解决方案
Arrays.sort(list, new Comparator<File>() {
public int compare(File f1, File f2) {
return Long.compare(f1.lastModified(), f2.lastModified());
}
});
Comparator 在上次修改日期上运行良好,但是当我使用以下代码尝试时。结果和之前一样。
Arrays.sort(list, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
return o1.getName().compareTo(o2.getName());
}
});
在我的 Windows 资源管理器中,如下所示。我已经对文件名进行了排序。
我的控制台输出显示如下。
谢谢
【问题讨论】:
-
为什么处理顺序很重要?如果是这样,那么文件名约定应该反映这一点,以避免目录和基于字符串的排序的差异,从而明确地相同。
-
你的操作系统是什么,“在我的目录中当我进行排序时显示的第一个文件是”是什么意思?
-
文件的顺序将取决于您用来查看它们的任何软件(例如 Windows 上的资源管理器)。您需要使用使用相同逻辑的比较器。
-
嗨@RC。我的意思是,在我的 Windows 资源管理器中,当我单击标题栏时,名称会被排序。
标签: java