ProjectDefy
ProjectDefy

Reputation: 101

Trying to get file name of the largest file

So I am learning recursion right now and I know how to get the largest file size in a folder that's chosen in JFileChooser.

I just can't for the life of me can't figure out how to get the name of that file after it's found. Here's the method to getting the largestFileSize. How would I go about getting the name of that file?

public static long largestFileSize(File f) {
    if (f.isFile()) {
        return f.length();
    } else {
        long largestSoFar = -1;

        for (File file : f.listFiles()) {
            largestSoFar = Math.max(largestSoFar, largestFileSize(file));
        }
        return largestSoFar;
    }
}

Upvotes: 5

Views: 619

Answers (2)

Hans Brende
Hans Brende

Reputation: 8617

Just do

public static File largestFile(File f) {
    if (f.isFile()) {
        return f;
    } else {
        long largestSoFar = -1;
        File largestFile = null;
        for (File file : f.listFiles()) {
            file = largestFile(file);
            if (file != null) {
                long newSize = file.length();
                if (newSize > largestSoFar) {
                    largestSoFar = newSize;
                    largestFile = file;
                }
            }
        }
        return largestFile;
    }
}

then call:

largestFile(myFile).getName();

Upvotes: 1

jiaweizhang
jiaweizhang

Reputation: 819

String fileName = file.getName()

Since it's impractical to return both the size of a file and the name, why don't you return the File and then get its size and name from that?

public static File largestFile(File f) {
    if (f.isFile()) {
        return f;
    } else {
        File largestFile = null;

        for (File file : f.listFiles()) {
            // only recurse largestFile once
            File possiblyLargeFile = largestFile(file);
            if (possiblyLargeFile != null) {
                if (largestFile == null || possiblyLargeFile.length() > largestFile.length()) {
                    largestFile = possiblyLargeFile;
                }
            }
        }
        return largestFile;
    }
}

And then you can do this:

String largestFileName = largestFile(file).getName();
long largestFileSize = largestFile(file).length();

EDIT: Returns largest File in any of the subdirectories. Returns null if no files exist in the subdirectories.

Upvotes: 6

Related Questions