Fastest way to read a file line by line with 2 sets of Strings on each line?

拟墨画扇 提交于 2019-11-27 01:37:31

问题


What is the fastest way I can read line by line with each line containing two Strings. An example input file would be:

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

There are always two sets of strings on each line that I need even if there are spaces between the String e.g. "By Line"

Currently I am using

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

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

Is that efficient enough or is there a more efficient way using standard JAVA API (no outside libraries please) Any help is appreciated Thanks!


回答1:


It depends what do you mean when you say "efficient." From the point of view of performance it is OK. If you are asking about the code style and size, I pesonally do almost you do with a small correction:

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

For reading from STDIN Java 6 offers you yet another way. Use class Console and its methods

readLine() and 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);
        }
    }
}

The result:

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>



回答3:


If you want separate two sets of String you can do this in that way:

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();


来源:https://stackoverflow.com/questions/5035894/fastest-way-to-read-a-file-line-by-line-with-2-sets-of-strings-on-each-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!