17

各行に2つの文字列が含まれている状態で、行ごとに読み取ることができる最速の方法は何ですか。入力ファイルの例は次のとおりです。

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

文字列の間にスペースがある場合でも、各行には常に2セットの文字列があります(例:「行別」)。

現在使用しています

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

「効率的」とはどういう意味かによります。パフォーマンスの観点からはOKです。コードのスタイルとサイズについて質問している場合、私は個人的にほとんどの場合、小さな修正を加えます。

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

STDINから読むために、Java6はさらに別の方法を提供します。クラス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

2セットの文字列を別々にしたい場合は、次のように行うことができます。

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 に答える