Jok*_*ker 3 java file-io bufferedinputstream fileoutputstream
在工作时BufferedOutputStream发现它并没有抛出IOException我们在关闭流后写的时候.
为了验证我的结果,我检查FileOutputStream发现IOException一旦我们在关闭它之后尝试写它就扔了.
public class Test {
public static void main(String[] args) {
try {
// Created a byte[] barry1 barry2
byte[] barry1 = { '1', '3' };
byte[] barray2 = { '2', '4' };
OutputStream os = new BufferedOutputStream(
new FileOutputStream("abc.txt", false));
// Writing to stream
os.write(barry1);
os.close();
os.write(barray2); // this suceeds - bug
os = new FileOutputStream("abc.txt", true);
//Writing to stream
os.write(barry1);
os.close();
os.write(barray2); // crashes here, correct.
} catch (Exception e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
有人可以帮我这个,为什么这个行为有所不同?
在BufferedOutputStream上工作时发现它在关闭流后写入时不会抛出IOException.
该BufferedOutputStream代码根本就没有那种检查的-但是同样没有的FileOutputStream.在这两种情况下,只有当IO实际写入磁盘时,操作系统才会"抛出" IOException.检测到流已关闭的Java代码不是.顺便说一句,这可能意味着一些本机实现根本不会抛出.
为什么原因FileOutputStream是抛出异常上os.write(...),相对于BufferedOutputStream,是,它是立即写IO底层本地层.如果os.flush()在BufferedOutputStream之后添加调用,os.write()则会看到相同的异常,因为这会强制写出其内部缓冲区.
OutputStream os = new BufferedOutputStream(new FileOutputStream("abc.txt", false));
os.write(barry1);
os.close();
os.write(barray2); // this suceeds – unfortunate behavior
os.flush(); // adding this line throws an IOException
Run Code Online (Sandbox Code Playgroud)
在看BufferedOutputStream的close()方法(在实际FilterOutputStream基类),你可以看到输出流未设置为null或任何东西:
public void close() throws IOException {
try {
flush();
} catch (IOException ignored) {
}
out.close();
}
Run Code Online (Sandbox Code Playgroud)
我也不喜欢它在这里忽略IOExceptions的事实.哇.这告诉我,我们应该总是flush()手工打电话,close()这是我特别不做的模式.
现在将该代码与BufferedWriter.close():
public void close() throws IOException {
synchronized (lock) {
if (out == null) {
return;
}
try {
flushBuffer();
} finally {
out.close();
out = null; // good doggie
cb = null;
}
}
}
Run Code Online (Sandbox Code Playgroud)
BufferedWriter.close()不吃异常,并设置委派的Writer是null.更好的IMO.
| 归档时间: |
|
| 查看次数: |
619 次 |
| 最近记录: |