该类中的getFreeSpaceKb(String path)方法FileSystemUtils可以帮助您计算驱动器或卷的可用空间(以千字节为单位)。
除了使用commons-io解决方案外,您还可以使用File.getFreeSpace()Java 1.6 API中提供的方法调用。您可以在以下链接中找到它的示例:如何获得磁盘的总空间和可用空间?
package org.nhooo.example.commons.io; import org.apache.commons.io.FileSystemUtils; import org.apache.commons.io.FileUtils; import java.io.IOException; public class DiskFreeSpace { public static void main(String[] args) { try { String path = "/Users/wayan"; long freeSpaceKB = FileSystemUtils.freeSpaceKb(path); long freeSpaceMB = freeSpaceKB / FileUtils.ONE_KB; long freeSpaceGB = freeSpaceKB / FileUtils.ONE_MB; System.out.println("Size of " + path + " = " + freeSpaceKB + " KB"); System.out.println("Size of " + path + " = " + freeSpaceMB + " MB"); System.out.println("Size of " + path + " = " + freeSpaceGB + " GB"); } catch (IOException e) { e.printStackTrace(); } } }
上面的代码的示例结果是:
Size of /Users/wayan = 70583428 KB Size of /Users/wayan = 68929 MB Size of /Users/wayan = 67 GB
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>