Common Java Cookbook

Edition: 0.19

Download PDF or Read on Scribd

Download Examples (ZIP)

10.4. Printing a Human-Readable File Size

10.4.1. Problem

You need to display the size of a file in kilobytes, megabytes, or gigabytes. Instead of displaying file sizes as 1,073,741,824 bytes, you want an approximate, human-readable size, such as 1 GB.

10.4.2. Solution

Use FileUtils.byteCountToDisplaySize() to produce a String containing an approximate, human-readable size. The following code passes the number of bytes in the file project.xml to FileUtils.byteCountToDisplaySize( ):

import org.apache.commons.io.FileUtils;
try {
    File file = new File("project.xml");
    long bytes = file.length( );
    String display = FileUtils.byteCountToDisplaySize( bytes );
    System.out.println("File: project.xml");
    System.out.println("  bytes: " + bytes );
    System.out.println("  size: " + display );
} catch( IOException ioe ) {
    System.out.println( "Error reading file length." );
}

This code prints out the number of bytes in the project.xml file, and the human-readable size "2 KB":

File: project.xml
  bytes: 2132
  size: 2 KB

10.4.3. Discussion

FileUtils contains three static variables—FileUtils.ONE_KB, FileUtils.ONE_MB, and FileUtils.ONE_GB—which represent the number of bytes in a kilobyte, megabyte, and gigabyte. FileUtils.byteCountToDisplaySize( ) divides the number of bytes by each constant until it finds a constant that can divide the number of bytes, discarding the remainder to create a human-readable value. For example, the value 2,123,022 is divided by FileUtils.ONE_GB, which returns a value of less than 1.0. The value is then divided by FileUtils.ONE_MB, which returns 2—the value used in the human-readable size "2 MB."

Warning

FileUtils.byteCountToDisplaySize( ) will not round the size of a file; a 2.9 MB file will have a display size of 2 MB. The byte count is divided by ONE_KB, ONE_MB, or ONE_GB, and the remainder is discarded.


Creative Commons License
Common Java Cookbook by Tim O'Brien is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License.
Permissions beyond the scope of this license may be available at http://www.discursive.com/books/cjcook/reference/jakartackbk-PREFACE-1.html. Copyright 2009. Common Java Cookbook Chunked HTML Output. Some Rights Reserved.