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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19057474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:45:09  来源:igfitidea点击:

How to avoid this java.io.IOException: No space left on device

java

提问by Avinash

If my space is full I get sometimes following exception

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

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)

Is there any way in Java to avoid this. I mean do not call write if no space

Java 中有什么方法可以避免这种情况。我的意思是如果没有空间就不要调用 write

采纳答案by Sotirios Delimanolis

Java 7 NIO offers the FileStoreclass to check the available size

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
        }
    }
}

Obviously you can still get an IOExceptionas nothing is atomic and other processes might be using the same disk, so keep that in mind and handle the exception accordingly.

显然你仍然可以得到一个,IOException因为没有什么是原子的,其他进程可能正在使用同一个磁盘,所以请记住这一点并相应地处理异常。

回答by Scott Heaberlin

Just look at the File class documentation.

只需查看 File 类文档

These new methods also include:

这些新方法还包括:

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