gpt4 book ai didi

java - OpenCSV 从最后一行和特定列获取值

转载 作者:行者123 更新时间:2023-12-01 14:37:07 29 4
gpt4 key购买 nike

我试图从分号分隔的文件中的倒数第二行和第三列获取值。我无法坐下来获取倒数第二行和第三列的值。

我一直在寻找一种方法来实现这一目标,但没有结果。如果有人能用一个例子为我指明正确的方向,我将不胜感激。

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

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

最佳答案

虽然您正在阅读第二nd最后一行,但这可能可能会更改为第三rd或第四th 最后几行。在这里做一个定制的解决方案肯定会很脆弱。因此使用循环缓冲区,例如 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]);

注意:您将需要 Generics version of Commons-Collections对于这个例子。

关于java - OpenCSV 从最后一行和特定列获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16386590/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com