Attempting to get the file name of the largest file

So, I am studying recursion right now, and I know how to get the maximum file size in the folder selected in JFileChooser.

I just can’t keep my life from understanding how to get the name of this file after it is discovered. Here is a way to get the largest FileSize. How can I get the name of this 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; } } 
+5
source share
2 answers
 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.

+6
source

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(); 
+1
source

Source: https://habr.com/ru/post/1236294/


All Articles