Java BufferedWriter, OutputStreamWriter able to write to closed FileOutputStream
Asked Answered
T

1

8

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.

Trimeter answered 16/3, 2010 at 19:47 Comment(0)
C
11

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)
Cutcliffe answered 16/3, 2010 at 19:55 Comment(3)
Thanks! Can't believe I didn't try that, Unit Tests get me so focused, I sometimes miss the obvious.Trimeter
Why would it not throw an exception at ow.write(65), though? The OutputStreamWriter isn't buffered.Pisces
If you read the javadoc for the OutputStreamWriter (the intro) you see that it is buffered too.Cutcliffe

© 2022 - 2024 — McMap. All rights reserved.