Resource leak after closing BufferedReader

I'm still learning Java, and I need help to understand why this code is wrong:

BufferedReader infile = new BufferedReader(new FileReader(file));
String regel = infile.readLine();
while (regel != null) {
    // Do something with regel.
    regel = infile.readLine();
}
infile.close();

I really don't see the problem, but Eclipse continues to report that there is a resource leak, and this infile is not closed.

(another detail, this code is in the try block, but I left it to stay simple)

+3
source share
3 answers

Eclipse complains because the link cannot be closed (for example, in Exception); here you should use a block finally- maybe so

BufferedReader infile = null;
try {
  infile = new BufferedReader(new FileReader(file));
  String regel = infile.readLine();
  while (regel != null) {
    // Do something with regel.
    regel = infile.readLine();
  }
} catch (Exception e) {
  e.printStackTrace(); // Log the exception.
} finally {
  if (infile != null) {
    infile.close(); // close the resource.
  }
}
+3
source

You should have a try / catch block.

You should also use the following:

while ((line = reader.readLine()) != null) {
 //do something with line;
    }
0
source

I think that Elliott Frisch is right and pointed out the main reason that the only thing I would add is that you should close the stream (in the finally block), because to ensure that any output buffers are flushed if the output was in otherwise successful, if the flash fails, the code must exit through an exception. Here is another example similar to what you are trying to solve, and make sure that you are looking at ( Guide 1-2: release resources in all cases ) http://www.oracle.com/technetwork/java/seccodeguide-139067. html

    final OutputStream rawOut = new FileOutputStream(file);
    try {
        final BufferedOutputStream out =
            new BufferedOutputStream(rawOut);
        use(out);
        out.flush();
    } finally {
        rawOut.close();
    }
0
source

All Articles