-1

I am trying get directory size but I can't get I guess because I get Always the same value The desired result is get the size of each independent directory. How can I achieve this?

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

I get this Output:

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
Fernando Pie
  • 895
  • 1
  • 12
  • 28
  • Just a side-note, don't practice smelling code like you have the identifier in your language. That's a bad habit and don't underestimate it even if you're just practicing something. – Giorgi Tsiklauri Apr 24 '19 at 16:25
  • 1
    If a method doesn’t behave as you expect, the first thing you should do is read that method’s documentation. – VGR Apr 24 '19 at 16:41

2 Answers2

2

getTotalSpace() doesn't return the file or folder size.

Returns the size of the partition named by this abstract pathname.

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

devgianlu
  • 1,547
  • 13
  • 25
1

Hi mind clarifying a little bit? Do you want the size of the files (how much data is in there) or how many files are in the given directory?

This counts the number of files:

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

This gets the size of the directory according to this 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);}