views:

864

answers:

1

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.

+3  A: 

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)
disown
Thanks! Can't believe I didn't try that, Unit Tests get me so focused, I sometimes miss the obvious.
craineum
Why would it not throw an exception at `ow.write(65)`, though? The OutputStreamWriter isn't buffered.
Michael Myers
If you read the javadoc for the OutputStreamWriter (the intro) you see that it is buffered too.
disown
You're right, I didn't see that.
Michael Myers