Get folder size

前端 未结 8 1116
生来不讨喜
生来不讨喜 2020-12-30 06:27

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.

8条回答
  •  有刺的猬
    2020-12-30 06:49

    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;
       }
    

    }

提交回复
热议问题