Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java BufferedWriter, OutputStreamWriter able to write to closed FileOutputStream

I was expecting the following code to throw an exception when I goto write data to the Stream:

File file = new File("test.txt");
FileOutputStream fs = new FileOutputStream(file);
OutputStreamWriter ow = new OutputStreamWriter(fs);
BufferedWriter writer = new BufferedWriter(ow);

fs.close();

try {
    ow.write(65);
    writer.write("test");
} catch (Exception e) {
    e.printStackTrace();
}

I realize that I should close the BufferedWriter, but in my current environment, it may be possible for the FileOutputStream to be closed before the BufferedWriter is closed. Shouldn't the FileOutputStream be throwing an IOException which should move up the chain until it hits my try/catch block and print the stack trace?

If I try to call fs.write(65), then it throws an exception.

like image 643
craineum Avatar asked Mar 16 '10 19:03

craineum


1 Answers

Try flushing after the write call. The buffered stream might not have tried to write the content to the underlying stream yet, and hence not realized that the underlying stream was closed.

EDIT:

Just tried it. With the code:

File file = new File("test.txt");
FileOutputStream fs = new FileOutputStream(file);
OutputStreamWriter ow = new OutputStreamWriter(fs);
BufferedWriter writer = new BufferedWriter(ow);

fs.close();

try {
    ow.write(65);
    writer.write("test");
    writer.flush();
} catch (Exception e) {
    e.printStackTrace();
}

you get the following exception:

java.io.IOException: Bad file descriptor
    at java.io.FileOutputStream.writeBytes(Native Method)
    at java.io.FileOutputStream.write(FileOutputStream.java:260)
    at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:202)
    at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:272)
    at sun.nio.cs.StreamEncoder.implFlush(StreamEncoder.java:276)
    at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:122)
    at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:212)
    at java.io.BufferedWriter.flush(BufferedWriter.java:236)
    at Test.main(Test.java:16)
like image 179
Alexander Torstling Avatar answered Sep 28 '22 12:09

Alexander Torstling