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

时间:2011-02-17 23:12:59

标签: java bufferedreader filereader

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

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

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

目前我正在使用

FileReader a = new FileReader(file);
            BufferedReader br = new BufferedReader(a);
            String line;
            line = br.readLine();

            long b = System.currentTimeMillis();
            while(line != null){

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

3 个答案:

答案 0 :(得分:39)

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

        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)

答案 1 :(得分: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>

答案 2 :(得分:1)

如果你想要单独的两组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();