按照规模从最大到最小排序代码输出的最简单方法是什么?这是一个检查从命令行传递的路径总大小的小代码。它显示目录中指定的目录文件以及目录中文件夹的总大小,我想按大小从大到小排序?将输出从最大到最小排序?
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;
}
}
张贴的代码被无用...发布一个示例输出 –