【问题标题】:Java BufferedWriter IOException "Too many open files" [duplicate]Java BufferedWriter IOException“打开的文件太多” [重复]
【发布时间】:2012-10-24 23:00:31
【问题描述】:

可能重复:
Java Too Many Open Files

这不是重复的,引用的问题不同,只有标题相同,请仔细阅读

这是我的文件写入函数

 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 = nullfstream 已经打开并且永远不会关闭。 (否则fstream 会被out.close() 关闭。)
  • 这个异常肯定发生在 new FileWriter() 中,而不是 new BufferedWriter() 中?

标签: java


【解决方案1】:

看看 ReadPropertiesFile() 的内部

CommonClass.ReadPropertiesFile("LogFilepath");

我想 close() 丢失了...

不好:

properties.load( new FileInputStream( PropertiesFilePath ));

更好:

InputStream is = new FileInputStream( PropertiesFilePath );
properties.load( is );
is.close();

但是 AMHO 可以在每次运行时读取一次 PropertiesFile,而不是每次需要属性值时

【讨论】:

  • 是的,如何关闭它?我只是在使用 properties.load(new FileInputStream(PropertiesFilePath))
  • @shabby -- 将其分成两个语句,以便捕获 FileInputStream。
【解决方案2】:

只需读取您的属性文件一次。

private static String filePath = CommonClass.ReadPropertiesFile("LogFilepath");
public static void WriteLog(String LogLine) {
    ...

CommonClass.ReadPropertiesFile 背后的代码可能有问题。

【讨论】:

  • LastCoder 好样的!我错过了这个,我以为我在关闭日志文件时遇到问题,谢谢
【解决方案3】:

尝试关闭文件:

        fstream.close();

我已经用你的代码测试过了。

【讨论】:

    猜你喜欢
    • 2011-05-16
    • 2011-01-03
    • 2012-07-05
    • 1970-01-01
    • 2016-07-18
    • 2011-06-29
    • 2011-09-10
    • 1970-01-01
    相关资源
    最近更新 更多