开发者

Regarding java file closing

i noticed in a java program the below line used to open a file and process it

BufferedReader inp = new BufferedReader(new FileReader(inputFile));

In the javaprogram the inp is not closed before exiting the program the below line is missing

if (inp != null)
    try {
       inp.close();
    } catch (IOException logOrIgnore) {}

The program has exits in a lot of开发者_运维问答 place but they had not closed the file. Do i need to put this line everywhere? If i dont close the file when the program exits will it be a issue. Does the garbage collector closes the file?


You should use try/finally:

Reader inp = new BufferedReader(new FileReader(inputFile));
try {
    // Do stuff with "inp"
} finally {
    IOUtils.closeQuietly(inp);
}

IOUtils is from Apache Commons IO. Its closeQuietly method is like your code snippet above: it calls close, and ignores any exceptions thrown.


The garbage collector does not close the file. If you know your program will not be long running or open many files, you can get away without closing the file. But otherwise you need to close it manually.


It sounds like you're using the BufferedReader without returning to the context in which it was declared (possibly an instance variable?). In that instance, you must close it manually upon each possible exit from your application. You cannot rely on the garbage collector to do this for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜