0

我正在尝试从分号分隔文件中的倒数第二行和第三列中获取值。我不能坐下来从倒数第二行和第三列中获取值。

我已经寻找一种方法来实现这一点,但它一直没有结果。如果有人能用一个例子指出我正确的方向,我将不胜感激。

这是我到目前为止的代码:

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

尽管您正在阅读倒数第二行,但这可能会更改为倒数第三行或倒数第四。在这里做一个定制的解决方案肯定会很脆弱。因此,使用诸如 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 。

于 2013-05-05T16:34:52.783 回答