2014-01-05 72 views
0

按照规模从最大到最小排序代码输出的最简单方法是什么?这是一个检查从命令行传递的路径总大小的小代码。它显示目录中指定的目录文件以及目录中文件夹的总大小,我想按大小从大到小排序?将输出从最大到最小排序?

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()返回长值...更新(由拉萨纳基于评论)

+2

文件#长度()返回长。也许Long.compare(file2.length() - file1.length())会更好 –

+0

@lassana谢谢;更新了我的答案.. –