How do I display a cleanly formatted file size?
Author: Deron Eriksson
Description: This Java tutorial describes how to display a nicely formatted file size using Commons IO.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)

The byteCountToDisplaySize() method of the FileUtils class of the ApacheSW Commons IOS library allows us to display a "human-readable" version of a file size. It takes a long representing the file size in bytes and returns a String. The FileSize class demonstrates this.

package test;



public class FileSize {

	public static void main(String[] args) {
		fileInfo(new File("test.txt"));
		fileInfo(new File("commons-codec-1.3.jar"));
		fileInfo(new File("BigFile.mp3"));

	public static void fileInfo(File file) {
		System.out.println("File name: " + file.getName());
		long fileSize = file.length();
		System.out.println("File size: " + fileSize);
		String fileSizeDisplay = FileUtils.byteCountToDisplaySize(fileSize);
		System.out.println("Size Display: " + fileSizeDisplay);

The console output of FileSize is shown below. We see the name, size in bytes, and value returned from FileUtils.byteCountToDisplaySize(fileSize) for three different files.

File name: test.txt
File size: 29
Size Display: 29 bytes

File name: commons-codec-1.3.jar
File size: 46725
Size Display: 45 KB

File name: BigFile.mp3
File size: 528474624
Size Display: 503 MB

Related Tutorials: