17

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

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(请不要使用外部库)任何帮助表示感谢谢谢!

4

3 回答 3

40

这取决于您所说的“高效”是什么意思。从性能的角度来看是可以的。如果您询问代码样式和大小,我个人几乎会做一些小的修正:

        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)

于 2011-02-17T23:25:30.523 回答
2
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>
于 2011-02-17T23:40:38.950 回答
1

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

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();
于 2011-02-17T23:28:08.240 回答