0

私はJavaテキストの解析に不慣れで、各行の形式がわかっている場合にファイルを解析するための最良の方法は何でしょうか。

各行に次の形式のファイルがあります。

Int; String、double; String、double; String、double; String、double; String、double

String、doubleがコンマで区切られたペアとして機能し、各ペアがセミコロンで区切られていることに注意してください。

いくつかの例:

1; art、0.1; computer、0.5; Programming、0.6; java、0.7; unix、0.3
2; 291,0.8;データベース、0.6;コンピューター、0.2; java、0.9;学部生、0.7
3;コーヒー、0.5;コロンビア、0.2; java、0.1;エクスポート、0.4;インポート、0.5

次のコードを使用して各行を読み取ります。

public static void main(String args[]) {
    try {
        // Open the file that is the first
        // command line parameter
        FileInputStream fstream = new FileInputStream("textfile.txt");
        // Get the object of DataInputStream
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        // Read File Line By Line
        while ((strLine = br.readLine()) != null) {
            // Print the content on the console             
            System.out.println(strLine);
        }
        // Close the input stream
        in.close();
    } catch (Exception e) {// Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }   
 }

前もって感謝します :)

4

3 に答える 3

4

Scanner初心者のために、クラスを使用することができます:

正規表現を使用してプリミティブ型と文字列を解析できるシンプルなテキストスキャナー。

于 2011-11-16T19:46:19.763 に答える
0

本当に「C」スタイルの解析を行おうとしている場合、「次の」フィールドに蓄積されている文字を含むバッファーはどこにありますか?フィールドセパレータが読み取られたかどうかを確認するチェックはどこにあり、行末/フィールドセパレータが読み取られたときに現在のフィールドを正しいデータ構造にフラッシュするコードはどこにありますか?

Javaの文字ごとの読み取りループは次のようになります

int readChar = 0;
while ((readChar = in.read()) != -1) {
   // do something with the new readChar.
}
于 2011-11-16T19:51:36.047 に答える
0

パターンを提供してスキャナーを使用できます

String input = "fish1-1 fish2-2";
java.util.Scanner s = new java.util.Scanner(input);
s.findInLine("(\\d+)");
java.util.regex.MatchResult result = s.match();
for (int i=1; i<=result.groupCount(); i++)
    System.out.println(result.group(i));
s.close(); 
于 2011-11-16T20:22:11.717 に答える