用File API可以获取指定目录的大小
freeSpace和usableSpace区别
FreeSpace:
Returns the number of unallocated bytes in the partition named by this abstract path name.
The returned number of unallocated bytes is a hint, but not a guarantee, that it is possible to use most or any of these bytes. The number of unallocated bytes is most likely to be accurate immediately after this call. It is likely to be made inaccurate by any external I/O operations including those made on the system outside of this virtual machine. This method makes no guarantee that write operations to this file system will succeed.
UsableSpace:
Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname. When possible, this method checks for write permissions and other operating system restrictions and will therefore usually provide a more accurate estimate of how much new data can actually be written than getFreeSpace.
The returned number of available bytes is a hint, but not a guarantee, that it is possible to use most or any of these bytes. The number of unallocated bytes is most likely to be accurate immediately after this call. It is likely to be made inaccurate by any external I/O operations including those made on the system outside of this virtual machine. This method makes no guarantee that write operations to this file system will succeed.
代码
public static void main(String[] args) {
File root = new File("/");
System.out.println(root.getTotalSpace()); //500068036608
System.out.println(root.getFreeSpace()); //44024229888
System.out.println(root.getUsableSpace()); //30446862336
System.out.println(readableFileSize(root.getTotalSpace())); //465.7 GB
System.out.println(readableFileSize(root.getFreeSpace())); //41 GB
System.out.println(readableFileSize(root.getUsableSpace())); //31.3 GB
}
/**
* 格式化文件大小
* 参考:https://stackoverflow.com/a/5599842/1253611
*
* @param size byte
* @return readable file size
*/
public static String readableFileSize(long size) {
if (size <= 0) return "0";
final String[] units = new String[]{"B", "kB", "MB", "GB", "TB"};
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}