![](/img/trans.png)
[英]Running sbt fails - java.io.IOException: No space left on device
[英]How to avoid this java.io.IOException: No space left on device
如果我的空間已滿,我有時會遇到異常
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.