cra*_*eum 8 java fileoutputstream bufferedwriter
当我将数据写入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();
}
Run Code Online (Sandbox Code Playgroud)
我意识到我应该关闭BufferedWriter,但在我当前的环境中,可能有可能在BufferedWriter关闭之前关闭FileOutputStream.FileOutputStream不应该抛出一个IOException,它应该向上移动直到它到达我的try/catch块并打印堆栈跟踪?
如果我尝试调用fs.write(65),那么它会抛出异常.
Ale*_*ing 10
写入调用后尝试刷新.缓冲流可能尚未尝试将内容写入底层流,因此未意识到底层流已关闭.
编辑:
刚试了一下.随着代码:
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();
}
Run Code Online (Sandbox Code Playgroud)
你得到以下例外:
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31343 次 |
| 最近记录: |