2012-02-21 36 views
0

我试图从 http://www.roseindia.net/java/beginners/java-read-file-line-by-line.shtml 一个例子,例子中的BufferReader未闭是,需要关闭BufferReader与否?请解释。关闭一个缓冲的读者是强制性

FileInputStream fstream = new FileInputStream("textfile.txt"); 
BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); 
String strLine; 
//Read File Line By Line 
while ((strLine = br.readLine()) != null) { 
    // Print the content on the console 
    System.out.println (strLine); 
} 
//Close the input stream 
in.close(); 
+0

这可能是一些帮助:http://stackoverflow.com/questions/1388602/do-i-need-to-close-both-filereader-and-bufferedreader – NINCOMPOOP 2012-02-21 10:51:37

+0

请不要使用DataInputStream来读取tex吨。不幸的是,这样的例子会被一次又一次地复制,所以你可以从你的例子中删除它。 http://vanillajava.blogspot.co.uk/2012/08/java-memes-which-refuse-to-die.html – 2013-01-31 00:11:33

+1

不要使用rose india的代码。多少次错误或质量差的代码是令人惊讶的。 – 2013-07-20 13:46:01

回答

8

始终关闭流。这是一个很好的习惯,可以帮助你避免一些奇怪的行为。调用close()方法也会调用flush(),因此您不必手动执行此操作。

那里收流的最佳地点可能是在finally块。如果你有这样的例子,并且在in.close()行之前发生异常,则该流不会被关闭。

如果你还链接流,你只能关闭最后一个和所有它关闭之前太。这意味着在你的例子中br.close() - 不是in.close();

try { 
    // do something with streams 
} catch (IOException e) { 
    // process exception - log, wrap into your runtime, whatever you want to... 
} finally { 
    try { 
     stream.close(); 
    } catch (IOException e) { 
     // error - log it at least 
    } 
} 

或者,你可以在Apache的共享库使用closeQuietly(java.io.InputStream)

0

由于底层流是封闭的,不是绝对必要关闭BufferedReader,即使它是一个很好的做法相反的顺序关闭所有Closeable S(相对于他们在被打开的顺序。)

+2

另外,周围的人会建议使用更可信的教程资源...... – 2012-02-21 10:52:07

5

从资源泄漏预防的角度来看,它不是严格必要关闭的包装流,如果你也已经关闭,它封装了流。然而,关闭包装的流可能会导致东西迷失(特别是在输出的情况下),所以最好关闭(仅)包装器,并依靠记录的行为来关闭包装器关闭包装流。 (这当然是一个标准的I/O包装类真!)


像亚历山大,我怀疑依托“玫瑰印度”例子的智慧。举例来说,这其中有在这两个明显的失误,没有半像样的Java程序员应该:

  • 流不是在finally块封闭。如果在打开和关闭之间抛出任何异常,将不会执行in.close()语句,并且应用程序将泄漏打开的文件描述符。经常这样做,你的应用程序将开始抛出意想不到的IOException s。

  • 的DataInputStream类在链中没有用处。相反,他们应该使用fstream作为InputStreamReader的参数。或者更好的是,使用FileReader


最后,这里是例子的修正版本:

BufferedReader br = new BufferedReader(new FileReader ("textfile.txt")); 
try { 
    String line; 
    while ((line = br.readLine()) != null) { 
     // Print the content on the console 
     System.out.println(line); 
    } 
} finally { 
    // Close the reader stack. 
    br.close(); 
} 

或使用Java 7的 “尝试与资源”:

try (BufferedReader br = new BufferedReader(new FileReader ("textfile.txt"))) { 
    String line; 
    while ((line = br.readLine()) != null) { 
     // Print the content on the console 
     System.out.println(line); 
    } 
} 
+1

如果在初始化BufferedReader时发生异常,该怎么办? FileReader将仍然打开。 – 2015-04-27 14:58:15

+0

假设你正在谈论我的答案中的代码,是的,它会。看看BufferedReader的源代码。但是,对于那个构造函数,唯一合理的例外是OOME。 – 2015-04-27 16:17:56