Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the size of the largest file in a directory?

Tags:

java

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?

like image 893
Kannan Ramamoorthy Avatar asked Dec 07 '25 03:12

Kannan Ramamoorthy


2 Answers

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!

like image 107
mavroprovato Avatar answered Dec 08 '25 15:12

mavroprovato


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.

Demo

like image 23
Fahim Parkar Avatar answered Dec 08 '25 16:12

Fahim Parkar