Java 获取文件夹大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3169380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:05:02  来源:igfitidea点击:

Get folder size

javafile-io

提问by Eric

Do you know how can I get the folder size in Java?

您知道如何在 Java 中获取文件夹大小吗?

The length() method in the File class only works for files, using that method I always get a size of 0.

File 类中的 length() 方法仅适用于文件,使用该方法我总是得到大小为 0。

回答by Bill K

Folders generally have a very small "Size", you can think of them as an index.

文件夹通常具有非常小的“大小”,您可以将它们视为索引。

All the programs that return a "Size" for a folder actually iterate and add up the size of the files.

所有为文件夹返回“大小”的程序实际上都会迭代并累加文件的大小。

回答by OJ287

Iterate over all subfolders in the folder and get the summary size of all files there.

遍历文件夹中的所有子文件夹并获取那里所有文件的摘要大小。

回答by AHOYAHOY

import java.io.File;

public class GetFolderSize {

    int totalFolder = 0;
    int totalFile = 0;

    public static void main(String args[]) {
        String folder = "C:/GetExamples";
        try {
            GetFolderSize size = new GetFolderSize();
            long fileSizeByte = size.getFileSize(new File(folder));
            System.out.println("Folder Size: " + fileSizeByte + " Bytes");
            System.out.println("Total Number of Folders: "
                + size.getTotalFolder());
            System.out.println("Total Number of Files: " + size.getTotalFile());
        } catch (Exception e) {}
    }

    public long getFileSize(File folder) {
        totalFolder++;
        System.out.println("Folder: " + folder.getName());
        long foldersize = 0;
        File[] filelist = folder.listFiles();
        for (int i = 0; i < filelist.length; i++) {
            if (filelist[i].isDirectory()) {
                foldersize += getFileSize(filelist[i]);
            } else {
                totalFile++;
                foldersize += filelist[i].length();
            }
        }
        return foldersize;
    }

    public int getTotalFolder() {
        return totalFolder;
    }

    public int getTotalFile() {
        return totalFile;
    }
}

回答by Claude Vedovini

Use apache-commons-io, there's a FileUtilsclass with a sizeOfDirectorymethods

使用 apache-commons-io,有一个FileUtils带有sizeOfDirectory方法的类

回答by emory

There is a slight error with simply recursively iterating over all subfolders. It is possible on some file systems to create circular directory structures using symbolic links as is demonstrated below:

简单地递归迭代所有子文件夹会出现轻微错误。在某些文件系统上可以使用符号链接创建循环目录结构,如下所示:

mkdir -- parents father/son
ln -sf ${PWD}/father father/son
ls father/son/father/son/father/son/father/son/

To guard against this error, you can use the java.io.File#getCanonicalPath method. The code below is a slight modification of a previous answer.

为了防止这个错误,你可以使用 java.io.File#getCanonicalPath 方法。下面的代码是对先前答案的轻微修改。

public static long getFileSize(File folder) throws IOException {
    return ( getFileSize ( folder , new HashSet < String > ( ) ) ) ;
}

public static long getFileSize(File folder, Set<String> history)
        throws IOException {
    long foldersize = 0;
    File[] filelist = folder.listFiles();
    for (int i = 0; i < filelist.length; i++) {
        System.err.println("HISTORY");
        System.err.println(history);
        boolean inHistory = history.contains(filelist[i].getCanonicalPath());
        history.add(filelist[i].getCanonicalPath());
        if (inHistory) {
            // skip it
        } else if (filelist[i].isDirectory()) {
            foldersize += getFileSize(filelist[i], history);
        } else {
            foldersize += filelist[i].length();
        }
    }
    return foldersize;
}

回答by Harry

import java.io.File;
import org.apache.commons.io.FileUtils;

public class FolderSize
{
  public static void main(String[] args)
   {
    long size = FileUtils.sizeOfDirectory(new File("C:/Windows/folder"));

    System.out.println("Folder Size: " + size + " bytes");
   }
}

回答by sns

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

}

}

回答by Snaf

Go through a folder, file by file, getting the size of each file and adding them to the variable size.

逐个文件地浏览文件夹,获取每个文件的大小并将它们添加到可变大小。

static int size=0;

 public static int folderSize(File folder){

    size = 0;

    File[] fileList = folder.listFiles();

    for(File file : fileList){
        if(!file.isFile()){ 
            folderSize(file);
        }
        size += file.length();
    }
    return size;
}