-
回首忆惘然
一个常见的模式是使用try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// process the line.
}}如果假设没有字符编码,则可以更快地读取数据。ASCI-7,但不会有太大的区别。你对数据的处理很可能需要更长的时间。编辑:一种较不常见的模式,它避免了line漏水。try(BufferedReader br = new BufferedReader(new FileReader(file))) {
for(String line; (line = br.readLine()) != null; ) {
// process the line.
}
// line is not visible here.}更新:在Java 8中,您可以做到try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.forEach(System.out::println);}注意:您必须将流放在试着用资源块,以确保对它调用#CLOSE方法,否则基础文件句柄在GC很久之后才会关闭。
-
富国沪深
可以指定缓冲区大小,也可以使用默认大小。对于大多数用途,缺省值都足够大。// Open the fileFileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));String strLine;
//Read File Line By Linewhile ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);}//Close the input streamfstream.close();
-
汪汪一只猫
一次爪哇-8发布(2014年3月),您将能够使用流:try (Stream<String> lines = Files.lines(Paths.get(filename), Charset.defaultCharset())) {
lines.forEachOrdered(line -> process(line));}打印文件中的所有行:try (Stream<String> lines = Files.lines(file, Charset.defaultCharset())) {
lines.forEachOrdered(System.out::println);}
-
有只小跳蛙
下面是一个包含完整错误处理和支持前Java 7字符集规范的示例。使用Java 7,您可以使用具有资源的尝试语法,这使代码更加简洁。如果您只想要默认的字符集,可以跳过InputStream并使用FileReader。InputStream ins = null; // raw byte-streamReader r = null; // cooked readerBufferedReader br = null; // buffered for readLine()try {
String s;
ins = new FileInputStream("textfile.txt");
r = new InputStreamReader(ins, "UTF-8"); // leave charset out for default
br = new BufferedReader(r);
while ((s = br.readLine()) != null) {
System.out.println(s);
}}catch (Exception e){
System.err.println(e.getMessage()); // handle exception}finally {
if (br != null) { try { br.close(); } catch(Throwable t) { /* ensure close happens */ } }
if (r != null) { try { r.close(); } catch(Throwable t) { /* ensure close happens */ } }
if (ins != null) { try { ins.close(); } catch(Throwable t) { /* ensure close happens */ } }}以下是Groovy版本,具有完全错误处理:File f = new File("textfile.txt");f.withReader("UTF-8") { br ->
br.eachLine { line ->
println line;
}}