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 ...
Get Jakarta Commons Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.