简体   繁体   中英

Getting the size of a folder in Java returns negative long

I am trying to get the length (file size) of a directory and I have made the following recursive method to do so, only I get some very strange results when I pass new File("C:\\\\Users\\\\UserName\\\\Desktop") as the parameter.

static long totalLength = 0;

// Method to get the size of a folder and its contents
private static long getFolderSize(File folder){
    if(folder.isDirectory()){
        File[] contents = folder.listFiles();
        for(File current : contents){
            if(current.isDirectory()){
                totalLength = totalLength +getFolderSize(current);
            }
            totalLength = totalLength + current.length();
        }
    }
    return totalLength;
} 

Interestingly though, some folders on my desktop do return the expected results when I pass them into the method. I just can't work out why either: I've done some debugging of the length of the individual files and none of them appear to be negative, but I still sometimes get negative results!

Any ideas would be appreciated! Thanks in advance

You are missing an else{} block on the isDirectory() if statement. As a result, you are calling File.length() on a directory, which is unspecified according to the documentation. It may well be returning a negative value.

Documentation on File.length() here: http://docs.oracle.com/javase/6/docs/api/java/io/File.html#length()

Your code should probably read:

 if(current.isDirectory()) {
    totalLength = totalLength +getFolderSize(current, initial);
  } else {
    totalLength = totalLength + current.length();
  }

Why don't you use an established library which already has this built in, such as:

Which also has tests to cover cases like this.

I think this is better stylistically:

    private static long getFolderSize(File f) {
        if(!f.isDirectory()) return f.length();
        long totalLength = 0;
        for (File current : f.listFiles()) {
            totalLength += getFolderSize(current);
        }
        return totalLength;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM