views:

156

answers:

4

How can I retrieve size of folder or file in java ?

+1  A: 

File.length() (Javadoc).

Note that this doesn't work for directories, or is not guaranteed to work.

For a directory, what do you want? If it's the total size of all files underneath it, you can recursively walk children using File.list() and File.isDirectory() and sum their sizes.

danben
+2  A: 

The File object has a length method:

f = new File("your/file/name");
f.length();
JesperE
+8  A: 
java.io.File file = new java.io.File("myfile.txt");
file.length();

This returns the length of the file in bytes or 0 if the file does not exist. There is no built-in way to get the size of a folder, you are going to have to walk the directory tree recursively (using the listFiles() method of a file object that represents a directory) and accumulate the directory size for yourself:

public static long folderSize(File directory) {
    long length = 0;
    for (File file : directory.listFiles()) {
        if (file.isFile())
            length += file.length();
        else
            length += folderSize(file);
    }
    return length;
}
Tendayi Mawushe
+1 like these ready to run examples
stacker
Be careful if you run this in the C: root directory on a Windows machine; there's a system file there which is (according to java.io.File) neither a file nor a directory. You might want to change the else-clause to check that the File is actually a directory.
Paul Clapham
Simple change to check the parameter to see if it is not a directory at the beginning of the method and return the length then the recursion is simpler - just add the call to self in the same method and then this supports passing in a file reference instead of a directory as well.
Kevin Brock
+2  A: 
public static long getFolderSize(File dir) {
    long size = 0;
    for (File file : dir.listFiles()) {
        if (file.isFile()) {
            System.out.println(file.getName() + " " + file.length());
            size += file.length();
        }
        else
            size += getFolderSize(file);
    }
    return size;
}
Vishal
@Vishal your code need to have a simple fix, in the recursive call, you should add the size to existing size not just assign to it. `size += getFolderSize(file);`
Teja Kantamneni
@Teja: Thanks for pointing out, but the changes will be in the if statement as well
Vishal