I need to find out the size of the largest file/folder in a directory. I have done it in the below way.
private static Long getSizeofLargestFile(String theRootFolder)
{
Long aLargestFileSize = 0L;
File aRootDir = new File(theRootFolder);
for (File aFile : aRootDir.listFiles())
{
if (aLargestFileSize < aFile.length())
{
aLargestFileSize = aFile.length();
}
}
return aLargestFileSize / (1024 * 1024);
}
Can there be a better way than this?
Not really.. You have to get the sizes of all files to find the largest, which is what you are doing.
The only thing I would advise against is the division in the return. If the largest file is less than one MB, then your method will return 0!
I would say instead of
return aLargestFileSize / (1024 * 1024);
go with
return aLargestFileSize;
I will write why in some time...
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args)
{
Long aLargestFileSize1 = (1024*1024)+2 + 0L;
Long aLargestFileSize2 = (1024*1024)+ 0L;
System.out.println("aLargestFileSize1 final is " + aLargestFileSize1/ (1024 * 1024));
System.out.println("aLargestFileSize2 final is " + aLargestFileSize2/ (1024 * 1024));
System.out.println("aLargestFileSize1 new is " + aLargestFileSize1);
System.out.println("aLargestFileSize2 new is " + aLargestFileSize2);
}
}
If you see output both are giving 1. But if you would had System.out.println("aLargestFileSize1 final is " + aLargestFileSize1);, then output would have been,
aLargestFileSize1 new is 1048578
aLargestFileSize2 new is 1048576
means first file is larger.
So, just use actual number in return.
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