本示例演示如何使用Apache Commons IO库的FileUtils类创建易于阅读的文件大小。该方法以字节为单位获取文件大小,并以字节,千字节,兆字节,千兆字节等形式返回人类可读的文件大小显示。byteCountToDisplaySize()
package org.nhooo.example.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("/Users/nhooo/Downloads/Java/JDK/jdk-6u7-linux-i586.bin"); 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); } }
这是我们程序的结果:
Name = jdk-6u7-linux-i586.bin Size = 78482905 Display = 74 MB
Maven依赖
<!-- http://repo1.maven.org/maven2/commons-io/commons-io/2.6/commons-io-2.6.jar --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency>