0

セミコロンで区切られたファイルの最後の 2 行目と 3 番目の列から値を取得しようとしています。最後から2番目の行と3番目の列から値を取得することはできません。

これを達成する方法を探しましたが、成果がありませんでした。誰かが例を挙げて正しい方向に向けてくれれば幸いです。

これは私がこれまでに持っているコードです:

private static void readmyfile() throws IOException {

    String csvFilename = "C:/test.csv";

    CSVReader reader = new CSVReader(new FileReader(csvFilename), ';', '\'', 1);
    String[] nextLine;

    int rowNumber=-1;

    nextLine=reader.readNext();
    while (nextLine!=null){
        rowNumber++;
        String speed = nextLine[rowNumber];
        System.out.println(speed);
        nextLine=reader.readNext();
    }
}

私のファイルは次のようにフォーマットされています:

Number; ID; NUM; Counter; Time
1;CCF;9999;1;18:07:05
1;CC8;8888;1;18:07:15
1;CC1;8888;1;18:07:15
1;DC7;1111;1;18:07:15
Date:;01/01/2000; Read:;5; on:;01.05; off:;02.04
4

1 に答える 1

1

最後の 2 行目を読んでいますが、これ3行または 4行に変更される可能性あります。ここでカスタムソリューションを実行すると、間違いなく脆弱になります. したがって、Apache のCircularFifoBufferなどの循環バッファーを使用すると、位置カウントを維持することなく行を追加できます。

CSVReader reader = new CSVReader(new FileReader(csvFilename), ';', '\'', 1);

int rowCount = 2;                                    // save last 2 lines
Buffer<String[]> savedBuffer = new CircularFifoBuffer<String[]>(rowCount); 
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
   savedBuffer.add(nextLine);
}

int columnIndex = 2; // zero based
System.out.println(savedBuffer.get()[columnIndex]);

注:この例では、Commons-Collectionsの Generics バージョンが必要です。

于 2013-05-05T16:34:52.783 に答える