按大小从最大到最小对这段代码的输出进行排序的最简单方法是什么?这是一个小代码,用于检查从命令行传递的路径的总大小。它显示了路径中指定的目录文件和目录中文件夹的总大小,我想按大小从最大到最小排序?
import java.io.File;
public class ShowSize{
public static void main(String[] args) {
ShowSize ss = new ShowSize();
ss.showFileSizes(new File(args[0]));
}
// this method get call from main first
public static void showFileSizes(File dir) {
// assign path from command line to an array using listFiles() method
File[] files = dir.listFiles();
// create a arrays of long to calculate a size of subdirectories
long [] fileSizes = new long[files.length];
for (int i = 0; i < files.length; i++) {
fileSizes[i] = calculateFileSize(files[i]);
//create a boolean variable to check if file is a type of FILE or DIR
boolean isDirectory = files[i].isDirectory();
//show the results
System.out.println(((isDirectory) ? "DIR" : "FILE") + " - "+ files[i].getAbsolutePath() + " "+ showFileSize(fileSizes[i]));
}
}
// this method get call from showFileSize() every time the new path get loaded.
public static long calculateFileSize(File file) {
long fileSize = 0L;
if (file.isDirectory()) {
File[] children = file.listFiles();
for (File child : children) {
fileSize += calculateFileSize(child);
}
} else {
fileSize = file.length();
}
return fileSize;
}
// get the size of file in nice and easy to read format
public static String showFileSize(long size) {
String unit = "bytes";
if (size > 1024) {
size = size / 1024;
unit = "kb";
}
if (size > 1024) {
size = size / 1024;
unit = "mb";
}
if (size > 1024) {
size = size / 1024;
unit = "gb";
}
return "(" + size + ")" + unit;
}
}
答案 0 :(得分:2)
按大小从最大到最小
对此代码的输出进行排序的最简单方法是什么
如果要按大小排序,请尝试以下代码:
Arrays.sort(files, new Comparator<File>() {
public int compare(File file1, File file2) {
return Long.compare(file2.length(), file1.length()); // or apply your logic
}
});
files
是File
<强> [UPDATE] 强>
length()
返回长值...更新(根据lassana的评论)