如何在Java目录中对文件进行排序?

这是我的代码,它有效!但我希望能够根据名称,大小,修改日期等对文件列表进行排序

import java.io.File;

import org.apache.commons.io.FileUtils;

public class StartingPoint {

public static void main(String[] args) {

File file = new File(

"/home/t/lectures");

File[] files = file.listFiles();

for (File f : files) {

System.out.println("File : " + f.getName() + " ["

+ FileUtils.byteCountToDisplaySize(f.length()) + "]");

}

}

}

回答:

Arrays.sort( files, new Comparator<File>() {

public int compare( File a, File b ) {

// do your comparison here returning -1 if a is before b, 0 if same, 1 if a is after b

}

} );

您可以定义许多不同的Comparator类来进行不同的比较,例如:

public class FileNameComparator implements Comparator<File> {

public int compare( File a, File b ) {

return a.getName().compareTo( b.getName() );

}

}

public class FileSizeComparator implements Comparator<File> {

public int compare( File a, File b ) {

int aSize = a.getSize();

int bSize = b.getSize();

if ( aSize == bSize ) {

return 0;

}

else {

return Integer.compare(aSize, bSize);

}

}

}

...

然后,您只需将它们换出:

Arrays.sort( files, new FileNameComparator() );

要么

Arrays.sort( files, new FileSizeComparator() );

以上是 如何在Java目录中对文件进行排序? 的全部内容, 来源链接: utcz.com/qa/424475.html

回到顶部