Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get folder size

Tags:

java

file-io

Do you know how can I get the folder size in Java?

The length() method in the File class only works for files, using that method I always get a size of 0.

like image 302
Eric Avatar asked Jul 02 '10 22:07

Eric


People also ask

How do I show folder size in Windows?

Locate the file in Windows File Explorer. Make a right click on it and click on the option "Properties" in the drop-down menu. A window named as "[foldername] Properties" will pop up showing the folder size in "Size" and space occupied on the disk at "Size on disk" boxes respectively.

How do I check the size of a folder in Linux?

How to view the file size of a directory. To view the file size of a directory pass the -s option to the du command followed by the folder. This will print a grand total size for the folder to standard output. Along with the -h option a human readable format is possible.

How do I get the size of a directory in PowerShell?

You can use the Get-ChildItem ( gci alias) and Measure-Object ( measure alias) cmdlets to get the sizes of files and folders (including subfolders) in PowerShell.


1 Answers

import java.io.File;

public class GetFolderSize {

    int totalFolder = 0;
    int totalFile = 0;

    public static void main(String args[]) {
        String folder = "C:/GetExamples";
        try {
            GetFolderSize size = new GetFolderSize();
            long fileSizeByte = size.getFileSize(new File(folder));
            System.out.println("Folder Size: " + fileSizeByte + " Bytes");
            System.out.println("Total Number of Folders: "
                + size.getTotalFolder());
            System.out.println("Total Number of Files: " + size.getTotalFile());
        } catch (Exception e) {}
    }

    public long getFileSize(File folder) {
        totalFolder++;
        System.out.println("Folder: " + folder.getName());
        long foldersize = 0;
        File[] filelist = folder.listFiles();
        for (int i = 0; i < filelist.length; i++) {
            if (filelist[i].isDirectory()) {
                foldersize += getFileSize(filelist[i]);
            } else {
                totalFile++;
                foldersize += filelist[i].length();
            }
        }
        return foldersize;
    }

    public int getTotalFolder() {
        return totalFolder;
    }

    public int getTotalFile() {
        return totalFile;
    }
}
like image 158
AHOYAHOY Avatar answered Oct 13 '22 21:10

AHOYAHOY