使用 Java 查找可用磁盘空间
java programming java8object oriented programming
java.io.File 类提供以下有用的方法来找出可用的磁盘空间。
Sr.No. | 方法 &说明 |
---|---|
1 | public long getFreeSpace() 返回此抽象路径名命名的分区中未分配的字节数。 |
2 | public long getTotalSpace() 返回此抽象路径名命名的分区的大小。 |
3 | public long getUsableSpace() 返回此虚拟机在此抽象路径名命名的分区上可用的字节数。 |
以下示例展示了上述用法方法。
示例最终
import java.io.File; import java.text.NumberFormat; public class Tester { public static void main(String[] args) { NumberFormat numberFormat = NumberFormat.getInstance(); numberFormat.setMaximumFractionDigits(2); File cDrive = new File("C:\"); double freeSpace = cDrive.getFreeSpace(); double usableSpace = cDrive.getUsableSpace(); double totalSpace = cDrive.getTotalSpace(); double oneGB = 1024 * 1024 * 1024; System.out.println("可用空间:" + numberFormat.format(freeSpace/oneGB) + " GB"); System.out.println("可用空间:" + numberFormat.format(usableSpace/oneGB) + " GB"); System.out.println("总空间:" + numberFormat.format(totalSpace/oneGB) + " GB"); } }
输出
可用空间:11.66 GB 可用空间:11.66 GB 总空间:97.56 GB