How to avoid this java.io.IOException: there is no space on the device

If my space is full, I sometimes get an 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 don't call write if there is no space

+6
source share
2 answers

Java 7 NIO offers FileStore class to check 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 , since nothing is atomic, and other processes can use the same drive, so keep that in mind and handle the exception accordingly.

+8
source

Just take a look at the documentation

+1
source

Source: https://habr.com/ru/post/954804/


All Articles