This example demonstrates how to create a human-readable file size using the FileUtils
class of the Apache Commons IO library. The byteCountToDisplaySize()
method take the file size in bytes and return a human-readable display of the file size in bytes, kilobytes, megabytes, gigabytes, etc.
package org.kodejava.commons.io;
import org.apache.commons.io.FileUtils;
import java.io.File;
public class ReadableFileSize {
public static void main(String[] args) {
File file = new File("D:/Downloads/jdk-17_windows-x64_bin.exe");
long size = file.length();
String display = FileUtils.byteCountToDisplaySize(size);
System.out.println("Name = " + file.getName());
System.out.println("Size = " + size);
System.out.println("Display = " + display);
}
}
Here are the results of our program:
Name = jdk-17_windows-x64_bin.exe
Size = 159373640
Display = 151 MB
Maven Dependencies
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.14.0</version>
</dependency>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024