逐行读取文件的最快方法是每行有2组字符串?

我可以逐行读取每行包含两个字符串的最快方法是什么。 示例输入文件将是:

Fastest, Way To, Read One, File Line, By Line .... can be a large file 

即使字符串之间有空格,每行也总是有两组字符串,例如“By Line”

目前我正在使用

 FileReader a = new FileReader(file); BufferedReader br = new BufferedReader(a); String line; line = br.readLine(); long b = System.currentTimeMillis(); while(line != null){ 

是否足够有效或使用标准JAVA API有更高效的方式(请不要外部库)任何帮助表示赞赏谢谢!

这取决于你说“高效”时的意思。 从性能的角度来看,这是可以的。 如果你问的是代码风格和大小,我几乎可以做一些小的修正:

  BufferedReader br = new BufferedReader(new FileReader(file)); String line; while((line = br.readLine()) != null) { // do something with line. } 

对于STDIN的阅读,Java 6为您提供了另一种方式。 使用类Console及其方法

readLine()readLine(fmt, Object... args)

 import java.util.*; import java.io.*; public class Netik { /* File text is * this, is * a, test, * of, the * scanner, I * wrote, for * Netik, on * Stack, Overflow */ public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new File("test.txt")); sc.useDelimiter("(\\s|,)"); // this means whitespace or comma while(sc.hasNext()) { String next = sc.next(); if(next.length() > 0) System.out.println(next); } } } 

结果:

 C:\Documents and Settings\glowcoder\My Documents>java Netik this is a test of the scanner I wrote for Netik on Stack Overflow C:\Documents and Settings\glowcoder\My Documents> 

如果你想要单独的两组String,你可以这样做:

 BufferedReader in = new BufferedReader(new FileReader(file)); String str; while ((str = in.readLine()) != null) { String[] strArr = str.split(","); System.out.println(strArr[0] + " " + strArr[1]); } in.close();