Java中按名称排序文件与Windows资源管理器不同
我有一个简单的Java程序,它读取文件目录并输出文件列表。 我按名称对文件进行排序:Java中按名称排序文件与Windows资源管理器不同,java,windows-explorer,Java,Windows Explorer,我有一个简单的Java程序,它读取文件目录并输出文件列表。 我按名称对文件进行排序: String [] files = dirlist.list(); files = sort(files); 我的问题是,它按名称排序的方式与Windows资源管理器不同 例如,如果我有以下文件:abc1.doc、abc12.doc、abc2.doc Java的排序如下: abc1.doc abc12.doc abc2.doc abc1.doc abc2.doc abc12.doc Arrays.so
String [] files = dirlist.list();
files = sort(files);
我的问题是,它按名称排序的方式与Windows资源管理器不同
例如,如果我有以下文件:abc1.doc、abc12.doc、abc2.doc
Java的排序如下:
abc1.doc
abc12.doc
abc2.doc
abc1.doc
abc2.doc
abc12.doc
Arrays.sort(files, new WindowsExplorerStringComparator());
在Windows资源管理器中打开文件夹时,文件的排序如下:
abc1.doc
abc12.doc
abc2.doc
abc1.doc
abc2.doc
abc12.doc
Arrays.sort(files, new WindowsExplorerStringComparator());
如何让Java像在Windows资源管理器中那样对文件进行排序?
这是Windows的把戏吗?Windows资源管理器使用自己的算法。为了像资源管理器一样对文件进行排序,您应该创建一个自定义比较器来执行以下操作:
public class WindowsExplorerStringComparator implements Comparator<String>
{
private String str1, str2;
private int pos1, pos2, len1, len2;
public int compare(String s1, String s2)
{
str1 = s1;
str2 = s2;
len1 = str1.length();
len2 = str2.length();
pos1 = pos2 = 0;
int result = 0;
while (result == 0 && pos1 < len1 && pos2 < len2)
{
char ch1 = str1.charAt(pos1);
char ch2 = str2.charAt(pos2);
if (Character.isDigit(ch1))
{
result = Character.isDigit(ch2) ? compareNumbers() : -1;
}
else if (Character.isLetter(ch1))
{
result = Character.isLetter(ch2) ? compareOther(true) : 1;
}
else
{
result = Character.isDigit(ch2) ? 1
: Character.isLetter(ch2) ? -1
: compareOther(false);
}
pos1++;
pos2++;
}
return result == 0 ? len1 - len2 : result;
}
private int compareNumbers()
{
int end1 = pos1 + 1;
while (end1 < len1 && Character.isDigit(str1.charAt(end1)))
{
end1++;
}
int fullLen1 = end1 - pos1;
while (pos1 < end1 && str1.charAt(pos1) == '0')
{
pos1++;
}
int end2 = pos2 + 1;
while (end2 < len2 && Character.isDigit(str2.charAt(end2)))
{
end2++;
}
int fullLen2 = end2 - pos2;
while (pos2 < end2 && str2.charAt(pos2) == '0')
{
pos2++;
}
int delta = (end1 - pos1) - (end2 - pos2);
if (delta != 0)
{
return delta;
}
while (pos1 < end1 && pos2 < end2)
{
delta = str1.charAt(pos1++) - str2.charAt(pos2++);
if (delta != 0)
{
return delta;
}
}
pos1--;
pos2--;
return fullLen2 - fullLen1;
}
private int compareOther(boolean isLetters)
{
char ch1 = str1.charAt(pos1);
char ch2 = str2.charAt(pos2);
if (ch1 == ch2)
{
return 0;
}
if (isLetters)
{
ch1 = Character.toUpperCase(ch1);
ch2 = Character.toUpperCase(ch2);
if (ch1 != ch2)
{
ch1 = Character.toLowerCase(ch1);
ch2 = Character.toLowerCase(ch2);
}
}
return ch1 - ch2;
}
}
先按字符串排序,然后按名称长度排序。看起来是这样的
但是,您可以使用并提供自定义的
比较器
,以便它像Windows资源管理器一样进行排序。这是在Java中实现它的另一种尝试:
简而言之,它将两个字符串拆分为字母-数字部分进行比较,并以特定的方式对这些部分进行比较,以实现这种排序
因此,它的IMHO更具可读性。请看,我想补充一点:名为“files”的参数必须是String[]类型