سؤال

What is the easiest way to sort the output of this code by size from largest to smallest? It's a small code which check total size of path passed from command line. It shows the file of the directory specify in a path and a total size of folders inside the directory, which I want to sort by size from largest to smallest?

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;
}   
}
هل كانت مفيدة؟

المحلول

What is the easiest way to sort the output of this code by size from largest to smallest

If you want to sort by size try the following code:

Arrays.sort(files, new Comparator<File>() {
    public int compare(File file1, File file2) {
        return Long.compare(file2.length(), file1.length()); // or apply your logic
    }
});

Where files is an array of File

[UPDATE] length() returns long value... updated (based on comment by lassana)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top