实现说明
整个示例围绕类 DiskCapacityProbe组织。
使用要点
- 直接运行文件,输出会带上标签,比如
store :、total MiB :、unalloc MiB :——输出的每一行都能指回产生它的那次调用。
常见问题
运行「FileStore 探测磁盘容量」会打印什么?
整个文件跑完,输出行以 store :、total MiB :、unalloc MiB : 这类前缀开头。
核心语句
FileStore store = Files.getFileStore(Path.of("."));
long unallocated = store.getUnallocatedSpace();
long usable = store.getUsableSpace();
代码示例
import java.io.IOException;
import java.nio.file.FileStore;
import java.nio.file.Files;
import java.nio.file.Path;
public class DiskCapacityProbe {
public static void main(String[] args) throws IOException {
// the volume holding the current working directory
FileStore store = Files.getFileStore(Path.of("."));
long total = store.getTotalSpace();
long unallocated = store.getUnallocatedSpace();
long usable = store.getUsableSpace();
System.out.println("store : " + store.name() + " (" + store.type() + ")");
System.out.println("total MiB : " + total / (1024 * 1024));
System.out.println("unalloc MiB : " + unallocated / (1024 * 1024));
System.out.println("usable MiB : " + usable / (1024 * 1024));
// usable <= unallocated: usable also subtracts quotas and other reservations
// probe capacity before writing, turning "disk full" into a predictable degradation instead of a mid-run IOException
if (usable < 64L * 1024 * 1024) {
System.out.println("low disk: refuse to start background writer");
}
}
}