简体   繁体   中英

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

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 7 NIO offers the FileStore class to check the available size

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 IOException as nothing is atomic and other processes might be using the same disk, so keep that in mind and handle the exception accordingly.

Just look at the File class documentation .

These new methods also include:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM