Get file/directory size using Java 7 new IO

淺唱寂寞╮ 提交于 2019-12-18 13:52:19

问题


How can I get the size of a file or directory using the new NIO in java 7?


回答1:


Use Files.size(Path) to get the size of a file.

For the size of a directory (meaning the size of all files contained in it), you still need to recurse manually, as far as I know.




回答2:


Here is a ready to run example that will also skip-and-log directories it can't enter. It uses java.util.concurrent.atomic.AtomicLong to accumulate state.

public static void main(String[] args) throws IOException {
    Path path = Paths.get("c:/");
    long size = getSize(path);
    System.out.println("size=" + size);
}

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

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



回答3:


MutableLong size = new MutableLong();
Files.walkFileTree(directoryPath, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                size.add(attrs.size());
            }
}

This would calculate the size of all files in a directory. However, note that all files in the directory need to be regular files, as API specifies size method of BasicFileAttributes:

"The size of files that are not regular files is implementation specific and therefore unspecified."

If you stumble to unregulated file, you ll have either to not include it size, or return some unknown size. You can check if file is regular with

BasicFileAttributes.isRegularFile()


来源:https://stackoverflow.com/questions/7255592/get-file-directory-size-using-java-7-new-io

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!