已解决,简而言之:问题是我写入了已关闭的 FileOutputStream
我注意到使用 FileOutputStream 类有一些奇怪的语义。
如果我使用以下代码创建 FileOutputStream:
try {
File astDumpFile = new File(dumpASTPath);
if(!astDumpFile.exists()) {
astDumpFile.createNewFile();
}
astDumpStream = new FileOutputStream(dumpASTPath);
} catch( IOException e ) {
dumpAST = false;
//throw new IOException("Failed to open file for dumping AST: " + dumpASTPath);
System.out.println("Failed to open file for dumping AST: " + dumpASTPath);
}
在程序的开头(astDumpStream
是一个成员变量)。然后,如果我稍后(大约 3 秒后)将字符串数据写入文件,我会得到一个 IOException:流已关闭
:
try {
String dotGraph = gpvisitor.getDotGraph();
astDumpStream.write(dotGraph.getBytes("UTF8"));
astDumpStream.flush();
astDumpStream.close();
} catch( IOException e ) {
System.out.println("Failed to dump AST to file: " + e.getMessage());
e.printStackTrace();
}
但是,如果我在写入之前直接复制用于创建 FileOutputStream
的精确代码,它就会按预期工作。
现在我想知道为什么如果我提前创建该对象会得到该异常,但如果我在使用它之前直接创建它就不会得到该异常。
编辑:异常(exception):
java.io.IOException: Stream Closed
at java.io.FileOutputStream.writeBytes(Native Method)
at java.io.FileOutputStream.write(FileOutputStream.java:305)
at MyClass.function(MyClass.java:208)
我刚刚注意到,即使出现异常,仍然有一些数据被写入文件。有趣的是,第一行已完全写入,然后除最后一行之外的所有后续行都丢失了。
如果我将写入的字符串 dotGraph
替换为更短的内容,则所有内容都会正确写入,但我仍然会遇到该异常。
编辑:环境信息:
[~]> lsb_release -a
Distributor ID: Debian
Description: Debian GNU/Linux testing (wheezy)
Release: testing
Codename: wheezy
[~]> java -version
java version "1.7.0_09"
Java(TM) SE Runtime Environment (build 1.7.0_09-b05)
Java HotSpot(TM) 64-Bit Server VM (build 23.5-b02, mixed mode)
最佳答案
收到 IOException
提示流已关闭的唯一原因是流已关闭。您必须跟踪代码才能找出发生这种情况的位置。一些不太明显的地方包括调用其他方法和 try
语句的 finally
block 。另一件需要注意的事情是将变量 astDumpStream
重新分配给不同的流(在引发 IOException
之前关闭 - 可能甚至在第一次分配给 astDumpStream 之前)
)。
除非您有一个单独的线程可能会在延迟后关闭流,否则时间似乎并不相关。
关于java - 文件输出流 : Stream closed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13404912/