10.4. Printing a Human-Readable File Size

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.

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

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.39.144