Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can closing a FileInputStream cause a "No Space Left on Device" error?

I am a bit confused with an error my program started throwing recently.

java.io.IOException: No space left on device
    at java.io.FileInputStream.close0(Native Method)
    at java.io.FileInputStream.close(FileInputStream.java:259)
    at java.io.FilterInputStream.close(FilterInputStream.java:155)

I am assuming that since this is a FileInputStream, that this file is being held in memory, and not on the physical disk. Memory levels look great, and as does disk space. This is especially confusing since it happens on the close of the FileInputStream. Thanks for any explanations you might have as to how this can occur.

EDIT: Code for review

if (this.file.exists()) {
            DataInputStream is = new DataInputStream(new FileInputStream(this.file));
            this.startDate = new DateTime(is.readLong(), this.timeZone);
            this.endDate = new DateTime(is.readLong(), this.timeZone);
            is.close();
        } 

As you can see above I am only opening the file, reading some content, and then closing the file.

like image 861
Judicator Avatar asked Jan 30 '13 14:01

Judicator


1 Answers

In this case, the IOException is thrown from the native method that closes the stream.

The reason it is defined to throw an exception is because the close operation performs a final flush - thus, if an IOException occurs during the flush it will be thrown.

There are several reasons for the exception you have received:

  • You may lack write permissions on the specific folder.

  • You may have exceeded your quota.

I also personally suggest that you use the following method of closing the stream:

if (this.file.exists()) {
    try {
        DataInputStream is = new DataInputStream(new FileInputStream(this.file));
        this.startDate = new DateTime(is.readLong(), this.timeZone);
        this.endDate = new DateTime(is.readLong(), this.timeZone);
    } catch (Exception ex) {
        // Handle the exception here
    } finally {
        is.close();
    }
}

You can also use IOUtils method closeQuietly that does not throw an exception 'cause in your case you are not changing the file and you are probably not interested in the result of the close method.

EDIT:

Henry is right. I read InputStream and automatically changed it in my mind to OutputStream.

A close operation on the InputStream does not change the file itself but can change the metadata of the file - such as last access time, etc.

like image 104
Michael Avatar answered Oct 07 '22 08:10

Michael