2014-02-06 39 views
3

我仍然在学习Java后仍有资源泄漏,我需要一些帮助理解为什么这个代码是错误的:关闭的BufferedReader

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

我实在看不出问题,但Eclipse的不断告诉有资源泄漏并且infile未关闭。

(一个更详细地,这个代码代表在try块,但我离开它离开保持简单)

+2

想想如果'readLine'抛出一个异常,会发生什么。 –

+0

Java 7支持[* AutoCloseable *](http://docs.oracle.com/javase/7/docs/api/java/lang/Au​​toCloseable.html) –

+0

试过http://www.compileonline.com上的代码带有try catch的/compile_java_online.php。它工作没有任何抱怨。 – Wajahat

回答

3

Eclipse是抱怨由于参考可以不被关闭(例如,在一个异常);这就是你可以使用一个finally块 - 也许像这样

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. 
    } 
} 
0

你应该有一个try/catch块。

另外,应使用以下代替:

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

我觉得艾略特弗里希是正确的,并指出主要的原因我想补充的唯一事情是你应该关闭流(在finally块),因为以确保在输出成功的情况下任何输出缓冲区都被刷新。如果刷新失败,代码应该通过异常退出。下面是另一个例子类似于你正在试图解决,并确保你看看(准则1-2:释放资源在所有情况下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(); 
    }