How can I retrieve size of folder or file in Java?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
in linux if you want to sort directories then du -hs * | sort -h
Source code:
Here's the best way to get a general File's size (works for directory and non-directory):
Edit: Note that this is probably going to be a time-consuming operation. Don't run it on the UI thread.
Also, here (taken from https://stackoverflow.com/a/5599842/1696171) is a nice way to get a user-readable String from the long returned:
For Java 8 this is one right way to do it:
It is important to filter out all directories, because the length method isn't guaranteed to be 0 for directories.
At least this code delivers the same size information like Windows Explorer itself does.
The
File
object has alength
method: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 thelistFiles()
method of a file object that represents a directory) and accumulate the directory size for yourself:WARNING: This method is not sufficiently robust for production use.
directory.listFiles()
may returnnull
and cause aNullPointerException
. Also, it doesn't consider symlinks and possibly has other failure modes. Use this method.