-6ren"> -我很难过...假设我有这个目录树: {someRoot}/ {someRoot}/bar/ {someRoot}/bar/file1.txt {someRoot}/foo/ {someRoot}/fo-6ren">
gpt4 book ai didi

java - "directories-first"订单的比较器<文件>

转载 作者:行者123 更新时间:2023-11-30 05:58:19 27 4
gpt4 key购买 nike

我很难过...假设我有这个目录树:

{someRoot}/
{someRoot}/bar/
{someRoot}/bar/file1.txt
{someRoot}/foo/
{someRoot}/foo/baz/
{someRoot}/foo/baz/file3.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/file2.txt
{someRoot}/aardvark.txt
{someRoot}/food.txt
{someRoot}/zebra.txt

您会注意到顺序。调用此 order1。在每个阶段,目录先于文件。 (注意: bar/file1.txt 出现在 foo 之前,因此在全局范围内,目录并不都出现在所有文件之前。)

如果我枚举这个目录树,然后递归枚举子目录,我将得到以下 List<File> , 排序 order2

{someRoot}/
{someRoot}/aardvark.txt
{someRoot}/bar/
{someRoot}/foo/
{someRoot}/food.txt
{someRoot}/zebra.txt
{someRoot}/bar/file1.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/baz/
{someRoot}/foo/file2.txt
{someRoot}/foo/baz/file3.txt

如果我创建简单的 Comparator<File> :

Comparator<File> fc = new Comparator<File>(){
@Override public int compare(File o1, File o2) {
return o1.compareTo(o2);
}
};

然后我排序,我从字典顺序得到这个顺序 (order3):

{someRoot}
{someRoot}/aardvark.txt
{someRoot}/bar
{someRoot}/bar/file1.txt
{someRoot}/foo
{someRoot}/food.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/baz
{someRoot}/foo/baz/file3.txt
{someRoot}/foo/file2.txt
{someRoot}/zebra.txt

但我不想要这种排序(它有问题:注意 food.txt 位于目录 foo 及其子项之间),我想要 order1。我怎样才能写一个比较器来得到它?

最佳答案

这在我的测试中有效。

new Comparator<File>() {
@Override
public int compare(File first, File second) {
if (first.isDirectory() && second.isDirectory())
return first.compareTo(second);

if (first.isDirectory())
return this.compareToFile(first, second);

if (second.isDirectory())
return -(this.compareToFile(second, first));

return this.compareFiles(first, second);
}

private int compareFiles(File first, File second) {
File firstParentFile = first.getParentFile();
File secondParentFile = second.getParentFile();

if (isSubDir(firstParentFile, secondParentFile))
return -1;

if (isSubDir(secondParentFile, firstParentFile))
return 1;

return first.compareTo(second);
}

private int compareToFile(File directory, File file) {
File fileParent = file.getParentFile();
if (directory.equals(fileParent))
return -1;

if (isSubDir(directory, fileParent))
return -1;

return directory.compareTo(file);
}

private boolean isSubDir(File directory, File subDir) {
for (File parentDir = directory.getParentFile(); parentDir != null; parentDir = parentDir.getParentFile()) {
if (subDir.equals(parentDir)) {
return true;
}
}

return false;
}

关于java - "directories-first"订单的比较器<文件>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4440765/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com