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

2022-09-02 23:31:55

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

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的更有效的方法(请不要使用外部库)任何帮助都值得赞赏 谢谢!


答案 1

这取决于你说“高效”是什么意思。从性能的角度来看,这是可以的。如果你问代码风格和大小,我基本上做了一个小的更正:

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

阅读STDIN Java 6为您提供了另一种方式。使用类控制台及其方法

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


答案 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>

推荐