13

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.

skaffman
  • 398,947
  • 96
  • 818
  • 769
Eric
  • 317
  • 3
  • 6
  • 10
  • What do you expect the folder "size" to be? The actual size of the folder in the file system or the size of all of the files within it? – TofuBeer Jul 02 '10 at 22:39

8 Answers8

28

Use apache-commons-io, there's a FileUtils class with a sizeOfDirectory methods

Claude Vedovini
  • 2,421
  • 21
  • 19
  • Warning, this method has a serious issue where it can throw an IllegalArgumentException while running. See https://issues.apache.org/jira/browse/IO-389 – Fhl Jan 13 '17 at 11:14
  • The bug that @Fhl mentioned has been fixed from version 2.5 of the commons-io library. – X09 Jan 25 '17 at 04:38
  • @Ozuf Can you please link to the changelog/source? Thanks – Fhl Jan 25 '17 at 12:58
  • @Fhl it is there in the link that you pasted above. – X09 Jan 25 '17 at 18:15
21
import java.io.File;
import org.apache.commons.io.FileUtils;

public class FolderSize
{
  public static void main(String[] args)
   {
    long size = FileUtils.sizeOfDirectory(new File("C:/Windows/folder"));

    System.out.println("Folder Size: " + size + " bytes");
   }
}
Harry
  • 4,705
  • 17
  • 73
  • 101
  • 1
    This method has a serious issue. It can throw an IllegalArgumentException while aggregating the file sizes. See https://issues.apache.org/jira/browse/IO-389 – Fhl Jan 13 '17 at 11:08
  • The bug that @Fhl mentioned has been fixed from version 2.5 of the commons-io library. – X09 Jan 25 '17 at 04:38
7
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;
    }
}
Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361
AHOYAHOY
  • 1,856
  • 4
  • 24
  • 34
4

There is a slight error with simply recursively iterating over all subfolders. It is possible on some file systems to create circular directory structures using symbolic links as is demonstrated below:

mkdir -- parents father/son
ln -sf ${PWD}/father father/son
ls father/son/father/son/father/son/father/son/

To guard against this error, you can use the java.io.File#getCanonicalPath method. The code below is a slight modification of a previous answer.

public static long getFileSize(File folder) throws IOException {
    return ( getFileSize ( folder , new HashSet < String > ( ) ) ) ;
}

public static long getFileSize(File folder, Set<String> history)
        throws IOException {
    long foldersize = 0;
    File[] filelist = folder.listFiles();
    for (int i = 0; i < filelist.length; i++) {
        System.err.println("HISTORY");
        System.err.println(history);
        boolean inHistory = history.contains(filelist[i].getCanonicalPath());
        history.add(filelist[i].getCanonicalPath());
        if (inHistory) {
            // skip it
        } else if (filelist[i].isDirectory()) {
            foldersize += getFileSize(filelist[i], history);
        } else {
            foldersize += filelist[i].length();
        }
    }
    return foldersize;
}
Community
  • 1
  • 1
emory
  • 10,725
  • 2
  • 30
  • 58
2

Iterate over all subfolders in the folder and get the summary size of all files there.

OJ287
  • 734
  • 1
  • 7
  • 15
0

Folders generally have a very small "Size", you can think of them as an index.

All the programs that return a "Size" for a folder actually iterate and add up the size of the files.

Bill K
  • 62,186
  • 18
  • 105
  • 157
0
public class DirectorySize {
   public static void main(String[] args) {
          // Prompt the user to enter a directory or a file
          System.out.print("Please Enter a Directory or a File: ");
          Scanner input = new Scanner(System.in);
          String directory = input.nextLine();

          // Display the size
          System.out.println(getSize(new File(directory)) + " bytes");
   }

   public static long getSize(File file) {
           long size = 0; // Store the total size of all files

           if (file.isDirectory()) {
                  File[] files = file.listFiles(); // All files and subdirectories
                  for (int i = 0; i < files.length; i++) {
                         size += getSize(files[i]); // Recursive call
               }
           }
           else { // Base case
                  size += file.length();
           }

           return size;
   }

}

naeemgik
  • 2,232
  • 4
  • 25
  • 47
0

Go through a folder, file by file, getting the size of each file and adding them to the variable size.

static int size=0;

 public static int folderSize(File folder){

    size = 0;

    File[] fileList = folder.listFiles();

    for(File file : fileList){
        if(!file.isFile()){ 
            folderSize(file);
        }
        size += file.length();
    }
    return size;
}
Snaf
  • 1