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;
}
}
du command -h option : Display sizes in human readable format (e.g., 1K, 234M, 2G). du command -s option : It shows only a total for each argument (summary). du command -x option : Skip directories on different file systems. sort command -r option : Reverse the result of comparisons.
To do this, use one of the following methods: Rename the file so that it has a shorter name. Rename one or more folders that contain the file so that they have shorter names. Move the file to a folder with a shorter path name.
Listing Files In Size Order Using the ls Command in Linux To list the directory contents in descending file size order, use the ls command along with the -IS argument. You will see the larger files at the top of the list descending to the smallest files at the bottom.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With