Here are various ways to get the size of a directory and file using the classes below in Java.
- File
- Files, Paths
- Java8 Stream
- Commons-io library
Let`s see with an example.
Calculate size with File class
File.length()
returns the size of the file. The unit is bytes.
You can get the file size as follows, and you can also convert it to other units.
File file = new File("/home/js/test/myfile/file1.txt");
if (file.exists()) {
double bytes = file.length();
double kilobytes = (bytes / 1024);
double megabytes = (kilobytes / 1024);
double gigabytes = (megabytes / 1024);
System.out.println("bytes : " + bytes);
System.out.println("kilobytes : " + kilobytes);
System.out.println("megabytes : " + megabytes);
System.out.println("gigabytes : " + gigabytes);
} else {
System.out.println("File does not exists!");
}
result
bytes : 169439.0
kilobytes : 165.4677734375
megabytes : 0.1615896224975586
gigabytes : 1.5780236572027206E-4
terabytes : 1.541038727737032E-7
However, if the above code is applied to Folder, it returns only 4096 bytes, which is the file size for Folder.
If the code below is executed, the file sizes under the /home/js/test/myfile
folder are not calculated and only 4096 bytes are returned.
System.out.println();
File folder = new File("/home/js/test/myfile");
double bytes = folder.length();
System.out.println("bytes : " + bytes);
// output:
// bytes : 4096.0
If you want to calculate the size of all sub-files as well, you need to search all the sub-files and find the sum of the sizes of the files as follows.
File folder = new File("/home/js/test/myfile");
long bytes = getFolderSize(folder);
System.out.println("bytes : " + bytes);
public static long getFolderSize(File folder) {
long length = 0;
File[] files = folder.listFiles();
int count = files.length;
for (int i = 0; i < count; i++) {
if (files[i].isFile()) {
length += files[i].length();
} else {
length += getFolderSize(files[i]);
}
}
return length;
}
The above code is implemented to search the file recursively. (recursive)
result
bytes : 7119049
Calculate file size using Files
You can browse the directory using Files in Java7. As you browse, if it`s a file and not a folder, just add up its size.
The following code is an example of calculating the size of the myfile folder.
Path folder = Paths.get("/home/js/test/myfile");
AtomicLong bytes = new AtomicLong(0);
try {
Files.walkFileTree(folder, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
bytes.addAndGet(attrs.size());
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("bytes : " + bytes);
result
bytes : 7119049
Calculate file size using stream
The Files class provides a Files.walk()
method. This method creates a Stream
subfile for the folder passed as an argument.
You can get the sum of the file sizes by filtering only the files in the Stream as follows:
Path folder = Paths.get("/home/js/test/myfile");
try {
long bytes = Files.walk(folder)
.filter(p -> p.toFile().isFile())
.mapToLong(p -> p.toFile().length())
.sum();
System.out.println("bytes : " + bytes);
} catch (IOException e) {
e.printStackTrace();
}
result
bytes : 7119049
Calculate file size using Commons-io
You can get the size of a directory more simply by using the Commons-io library.
To use Commons-io, in the case of a Gradle project, add the following to dependencies of build.gradle
.
dependencies {
compile group: 'commons-io', name: 'commons-io', version: '2.6'
...
}
For projects that use other build systems such as Maven, refer to mvnrepository.com and configure it.
Here is the code to calculate the file size in a directory.
File folder = new File("/home/js/test/myfile");
long bytes = FileUtils.sizeOfDirectory(folder);
System.out.println("bytes : " + bytes);
Returns the file size of the directory passed as an argument to FileUtils.sizeOfDirectory()
in bytes.
result
bytes : 7119049
Reference
Related Posts
- Java - Remove items from List while iterating
- Java - How to find key by value in HashMap
- Java - Update the value of a key in HashMap
- Java - How to put quotes in a string
- Java - How to put a comma (,) after every 3 digits
- BiConsumer example in Java 8
- Java 8 - Consumer example
- Java 8 - BinaryOperator example
- Java 8 - BiPredicate Example
- Java 8 - Predicate example
- Java 8 - Convert Stream to List
- Java 8 - BiFunction example
- Java 8 - Function example
- Java - Convert List to Map
- Exception testing in JUnit
- Hamcrest Collections Matcher
- Hamcrest equalTo () Matcher
- AAA pattern of unit test (Arrange/Act/Assert)
- Hamcrest Text Matcher
- Hamcrest Custom Matcher
- Why Junit uses Hamcrest
- Java - ForkJoinPool
- Java - How to use Futures
- Java - Simple HashTable implementation
- Java - Create a file in a specific path
- Java - Mockito의 @Mock, @Spy, @Captor, @InjectMocks
- Java - How to write test code using Mockito
- Java - Synchronized block
- Java - How to decompile a ".class" file into a Java file (jd-cli decompiler)
- Java - How to generate a random number
- Java - Calculate powers, Math.pow()
- Java - Calculate the square root, Math.sqrt()
- Java - How to compare String (==, equals, compare)
- Java - Calculate String Length
- Java - case conversion & comparison insensitive (toUpperCase, toLowerCase, equalsIgnoreCase)