String fileName = file.getName()
Since it is not practical to return both the file size and the name, why don't you return the file and then get its size and name from this?
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 it:
String largestFileName = largestFile(file).getName(); long largestFileSize = largestFile(file).length();
EDIT : returns the largest File in any of the subdirectories. Returns null if files do not exist in subdirectories.
source share