I have an application which has a director开发者_如何学Goy created into SDCard where I save photos. I would like to know how much space is using that dir on SDCard in order to show that info to the user.
I'm not sure if its the best solution but you could do something like that:
int totalSize = 0;
File root = new File("path to one of your file").getParentFile();
File[] files = root.listFiles();
for (File file: files) {
totalSize = totalSize + file.length();
}
Then totalSize contains the sum of all files in the directory in bytes. depending on the structure of your directory (e.g. are there any subdirectories?) you have to adapt the code.
Edit: After a little bit of researching I'm almost sure that there is no method in java which directly returns the size of a directory. See e.g. this link: http://forums.sun.com/thread.jspa?threadID=640296
However in this link http://www.codemiles.com/java/get-directory-size-in-java-t1242.html there is a recursive version of my code mentioned above to calculate any subdirectories if availiable.
There is also a small library which can do what you want:
http://commons.apache.org/io/api-release/index.html
However then you have to import this library. I personally would prefer to write this short method by myself.
精彩评论