开发者

Java BufferedWriter, OutputStreamWriter able to write to closed FileOutputStream

开发者 https://www.devze.com 2022-12-22 22:52 出处:网络
I was expecting the following code to throw an exception 开发者_高级运维when I goto write data to the Stream:

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.


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号