1

重複の可能性:
Javaで開いているファイルが多すぎます

これは重複ではありません。参照される質問は異なります。タイトルのみが同じです。よくお読みください

これは私のファイル書き込み機能です

 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);
            }
        }
    }
}

私もこの質問を見ましたが、それは役に立たないようです。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), 

特定の回数の呼び出しの後、後続の呼び出しごとにこのエラーが発生し続け、ファイルにテキストが書き込まれなくなります。私が完全に混乱している理由を誰かに教えてもらえますか?

前もって感謝します

4

3 に答える 3

3

ReadPropertiesFile()の内部を見てください

CommonClass.ReadPropertiesFile("LogFilepath");

close()が欠落していると思います...

悪い:

properties.load( new FileInputStream( PropertiesFilePath ));

より良い:

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

ただし、AMHO a PropertiesFileは、プロパティ値が必要になるたびではなく、実行ごとに1回読み取ることができます。

于 2012-10-15T19:04:48.350 に答える
2

プロパティファイルを一度読んでください。

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

CommonClass.ReadPropertiesFileの背後にあるコードはバグがある可能性があります。

于 2012-10-15T19:04:41.720 に答える
0

ファイルを閉じてみてください:

        fstream.close();

私はあなたのコードでそれをテストしました。

于 2012-10-15T19:13:13.827 に答える