【发布时间】:2012-10-24 23:00:31
【问题描述】:
这不是重复的,引用的问题不同,只有标题相同,请仔细阅读
这是我的文件写入函数
public static void WriteLog(String LogLine) {
String filePath = CommonClass.ReadPropertiesFile("LogFilepath");
BufferedWriter out = null;
try {
// Create file
FileWriter fstream = new FileWriter(filePath, true);
out = new BufferedWriter(fstream);
out.write(LogLine + "\r\n");
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
} finally {
//Close the output stream
if (out != null) {
try {
out.write("Closing stream\r\n");
out.close();
} catch (IOException ex) {
System.err.println("Error Closing stream: " + ex.getMessage());
Logger.getLogger(LogWritter.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
我也见过this question,但它似乎没有帮助,如果 close 是一个阻塞调用,那么它不应该出现这个问题。
但是当我过于频繁地调用 WriteLog 函数时,即在循环中我得到这个错误:
Error: (No such file or directory)
Could not load properties File, Exception: (Too many open files),
Error: (No such file or directory)
Could not load properties File, Exception: (Too many open files),
在特定数量的调用之后,在每次后续调用中,我都会不断收到此错误,并且文件中不再写入任何文本。谁能告诉我我完全糊涂的原因。
提前致谢
【问题讨论】:
-
您打开的文件太多。该进程具有在进程启动时指定的最大打开文件数,并且您已超出该限制。可能你没有在某处关闭文件。
-
@Hot Licks:这就是我要问的问题,我想在哪里关闭文件,我想我可以读到异常说“打开的文件太多”我想知道到底在哪里文件没有被关闭
-
@Shabby。不,如果
out != null,你关闭out。如果在out = ...上引发异常,则out = null和fstream已经打开并且永远不会关闭。 (否则fstream会被out.close()关闭。) -
这个异常肯定发生在 new FileWriter() 中,而不是 new BufferedWriter() 中?
标签: java