Java: get disk usage of a file or directory








  • Option 1:
    import java.io.File;
    
    public class FileUtil {
    
     public static long getDiskUsage(File f) {
      if (f.isFile()) {
       return f.length();
      } else {
       int total = 0;
       File[] fs = f.listFiles();
       if (fs != null) {
        for (int i = 0; i < fs.length; i++) {
         total += getDiskUsage(fs[i]);
        }
       }
       return total;
      }
    
     }
    
     public static void main(String[] args) {
      System.out.println(getDiskUsage(new File("/tmp/1.png")));
     }
    }
    
  • Option 2:
    import java.io.File;
    import java.io.FileFilter;
    
    public class DiskUsage implements FileFilter {
    
     private long _size = 0;
    
     public DiskUsage() {
    
     }
    
     @Override
     public boolean accept(File file) {
      if (file.isFile()) {
       _size += file.length();
      } else {
       file.listFiles(this);
      }
      return false;
     }
    
     public long getSize() {
      return _size;
     }
    
     public static void main(String[] args) {
      DiskUsage du = new DiskUsage();
      du.accept(new File("/tmp/1.png"));
      System.out.println(du.getSize());
     }
    }
    



No comments:

Post a Comment