计算目录或文件的大小

时间:2014-09-07 06:51:43

标签: java

这个程序花了太多时间来计算c:/ Windows下的windows目录。如何使它像操作系统一样快,给出了目录的大小。     


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

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

2 个答案:

答案 0 :(得分:0)

为什么不使用nio api,它比java.io更好,更快一点。如果用下面的代码行替换你的getSize()函数,你的性能会提高(40%)。

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

答案 1 :(得分:0)

尝试使用apache commons-io,你可以从here

获取它
 long size = FileUtils.sizeOfDirectory(new File("C:/Windows"));
 System.out.println("Folder Size: " + size + " bytes");