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
Using java-7 nio api, calculating the folder size can be done a lot quicker.
Here is a ready to run example that is robust and won't throw an exception. It will log directories it can't enter or had trouble traversing. Symlinks are ignored, and concurrent modification of the directory won't cause more trouble than necessary.
After lot of researching and looking into different solutions proposed here at StackOverflow. I finally decided to write my own solution. My purpose is to have no-throw mechanism because I don't want to crash if the API is unable to fetch the folder size. This method is not suitable for mult-threaded scenario.
First of all I want to check for valid directories while traversing down the file system tree.
Second I do not want my recursive call to go into symlinks (softlinks) and include the size in total aggregate.
Finally my recursion based implementation to fetch the size of the specified directory. Notice the null check for dir.listFiles(). According to javadoc there is a possibility that this method can return null.
Some cream on the cake, the API to get the size of the list Files (might be all of files and folder under root).
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()
andFile.isDirectory()
and sum their sizes.You need
FileUtils#sizeOfDirectory(File)
from commons-io.Note that you will need to manually check whether the file is a directory as the method throws an exception if a non-directory is passed to it.
WARNING: This method (as of commons-io 2.4) has a bug and may throw
IllegalArgumentException
if the directory is concurrently modified.If you want to use Java 8 NIO API, the following program will print the size, in bytes, of the directory it is located in.
The
calculateSize
method is universal forPath
objects, so it also works for files. Note that if a file or directory is inaccessible, in this case the returned size of the path object will be0
.In Java 8:
It would be nicer to use
Files::size
in the map step but it throws a checked exception.UPDATE:
You should also be aware that this can throw an exception if some of the files/folders are not accessible. See this question and another solution using Guava.