0

This program is taking too much time to calculate the windows directory under c:/Windows. How to make it as fast as Operating system gives size of a directory.


    import java.io.File;
    import java.util.Scanner;

public class DirectorySize {
    public static void main(String[] args) {
        // Prompt the user to enter a directory or a file
        System.out.println("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 total size of all files

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

        return size;
    }
}

  • One small improvement can be to check if the files[i] is a directory before making the recursive call. This will save a lot of needless recursive calls. – shlomi33 Sep 07 '14 at 07:07
  • Can use this solution: http://stackoverflow.com/questions/2149785/get-size-of-folder-or-file – BachT Sep 07 '14 at 07:08
  • BTW, why write this code alone? Someone else did it before you + probably optimized it! Look here org.apache.commons.io.FileUtils.sizeOfDirectory – shlomi33 Sep 07 '14 at 07:11
  • Probably cuz it's a homework assignment? – hd1 Sep 07 '14 at 07:38
  • You can do a bit better with threads. But it gets trickier. – Hot Licks Sep 07 '14 at 14:11

2 Answers2

0

Why are you not using nio api,which are better and a bit faster than java.io. If you replace your getSize() function with below line of code you will get around(40%) improvement in performance.

static long getSize(Path startPath) throws IOException {
        final AtomicLong size = new AtomicLong(0);
        Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file,
                    BasicFileAttributes attrs) throws IOException {
                size.addAndGet(attrs.size());
                return FileVisitResult.CONTINUE;
            }

            public FileVisitResult visitFileFailed(Path file, IOException exc)
                    throws IOException {
                // Skip folders that can't be traversed
                System.out.println("skipped: " + file + "e=" + exc);
                return FileVisitResult.CONTINUE;
            }
        });
        return size.get();
    }
dReAmEr
  • 6,986
  • 7
  • 36
  • 63
0

Try with apache commons-io you can get it from here

 long size = FileUtils.sizeOfDirectory(new File("C:/Windows"));
 System.out.println("Folder Size: " + size + " bytes");
SparkOn
  • 8,806
  • 4
  • 29
  • 34