Java BufferedWriter、OutputStreamWriter 能够写入关闭的 FileOutputStream
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2457571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java BufferedWriter, OutputStreamWriter able to write to closed FileOutputStream
提问by craineum
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?
我意识到我应该关闭 BufferedWriter,但在我当前的环境中,FileOutputStream 可能会在 BufferedWriter 关闭之前关闭。FileOutputStream 不应该抛出一个 IOException ,它应该向上移动链直到它碰到我的 try/catch 块并打印堆栈跟踪吗?
If I try to call fs.write(65), then it throws an exception.
如果我尝试调用 fs.write(65),则会引发异常。
采纳答案by Alexander Torstling
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.
在 write 调用后尝试刷新。缓冲流可能尚未尝试将内容写入底层流,因此没有意识到底层流已关闭。
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)