Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Still resource leak after closing BufferedReader

I'm still learning Java and I need some help understanding 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 keeps telling there is a resource leak and that infile isn't closed.

(one more detail, this code stands in a try block but I left it away to keep it simple)

like image 249
Brecht Vercruyce Avatar asked Feb 10 '26 22:02

Brecht Vercruyce


1 Answers

Eclipse is complaining because the reference may not be closed (for example, in an Exception); this is where you would use a finally block - perhaps like 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.
  }
}
like image 52
Elliott Frisch Avatar answered Feb 13 '26 14:02

Elliott Frisch