如何避免这种java.io.IOException:设备上没有剩余空间



如果我的空间已满,我有时会收到以下异常

java.io.IOException: No space left on device
        at java.io.FileOutputStream.writeBytes(Native Method)
        at java.io.FileOutputStream.write(FileOutputStream.java:282)
        at java.io.ObjectOutputStream$BlockDataOutputStream.drain(ObjectOutputStream.java:1847)
        at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(ObjectOutputStream.java:1756)
        at java.io.ObjectOutputStream.<init>(ObjectOutputStream.java:230)

Java中有什么方法可以避免这种情况。我的意思是如果没有空格,请不要调用写入

Java 7 NIO提供了FileStore类来检查可用大小

Path p = Paths.get("/your/file"); // where you want to write
FileSystem fileSystem = FileSystems.getDefault();
Iterable<FileStore> iterable = fileSystem.getFileStores();
Iterator<FileStore> it = iterable.iterator(); // iterate the FileStore instances
while(it.hasNext()) {
    FileStore fileStore = it.next();
    long sizeAvail = fileStore.getUsableSpace(); // or maybe getUnallocatedSpace()
    if (Files.getFileStore(p).equals(fileStore) { // your Path belongs to this FileStore
        if (sizeAvail > theSizeOfBytesYouWantToWrite) {
            // do your thing
        }
    }
}

显然,您仍然可以获得IOException,因为没有任何东西是原子的,并且其他进程可能使用相同的磁盘,因此请记住这一点并相应地处理异常。

只需查看 File 类文档即可。

这些新方法还包括:

public long getTotalSpace()
public long getFreeSpace()
public long getUsableSpace()