无法获取Java中目录的大小

时间:2019-04-24 16:19:51

标签: java file

我正在尝试获取目录大小,但是我猜不到,因为我总是获得相同的值。理想的结果是获取每个独立目录的大小。我该如何实现?

File file = new File(dir + "");                                                         
long totalSpace = file.getTotalSpace(); // espacio del disco en bytes
archivos.add(dir + " TS: "+totalSpace);                                                             
System.out.println(dir + " TS: "+totalSpace);

我得到以下输出:

C:\ TS: 550729170944
C:\$Recycle.Bin TS: 550729170944
C:\.Trash-1000 TS: 550729170944
C:\android-sdk TS: 550729170944
C:\AS2 TS: 550729170944
C:\Autodesk TS: 550729170944
C:\Boot TS: 550729170944
C:\cygwin64 TS: 550729170944
C:\ESD TS: 550729170944
C:\FacturacionElectronica TS: 550729170944
C:\Intel TS: 550729170944
C:\OneDriveTemp TS: 550729170944
C:\opt TS: 550729170944
C:\OSTotoFolder TS: 550729170944
C:\Pentaho TS: 550729170944
C:\PerfLogs TS: 550729170944
C:\production TS: 550729170944
C:\Program Files TS: 550729170944
C:\Program Files (x86) TS: 550729170944
C:\ProgramData TS: 550729170944
C:\QualityStats TS: 550729170944
C:\SQLServer2017Media TS: 550729170944
C:\SRI-DIMM TS: 550729170944
C:\temp TS: 550729170944
C:\UserGuidePDF TS: 550729170944
C:\Users TS: 550729170944

2 个答案:

答案 0 :(得分:2)

getTotalSpace()不返回文件或文件夹的大小。

  

返回此抽象路径名所命名的分区的大小。

https://docs.oracle.com/javase/7/docs/api/java/io/File.html#getTotalSpace()

答案 1 :(得分:1)

你的想法澄清了一点吗?您要文件的大小(其中有多少数据)还是给定目录中有多少文件?

这计算文件数:

new File(<directory path>).listFiles().length

这将根据此website

获取目录的大小
private long getFolderSize(File folder) {
long length = 0;
File[] files = folder.listFiles();

int count = files.length;

for (int i = 0; i < count; i++) {
    if (files[i].isFile()) {
        length += files[i].length();
    }
    else {
        length += getFolderSize(files[i]);
    }
}
return length;}

public void whenGetFolderSizeRecursive_thenCorrect() {
long expectedSize = 12607;

File folder = new File("src/test/resources");
long size = getFolderSize(folder);

assertEquals(expectedSize, size);}