在到达末尾后从头开始读取csv文件(Java、OpenCSV)
我想用OpenCSV和Java来计算一个特定的行数。我的csv文件。然后,我想解析文件的每一行并做一些事情。我发现了一些与我类似的问题,这些问题最常见的答案是使用循环来计算行数,因为CSVReader类没有计算它读取的文件行数的函数。我的问题是:在我计算行数之后,有没有一种方法可以在第一次循环后从头读取文件,而不创建新的CSVReader对象和字符串缓冲区?提前谢谢
编辑:我最终使用了CSVReader类的readAll()成员函数。它将整个文件存储到字符串数组列表中。每一行都是一个列表节点,该行的每个条目都是字符串数组中的一个字符串。通过这种方式,您也可以很容易地获得如下行数:
List<String[]> records = csvReader.readAll();
int no_of_rows = records.size();
import com.opencsv.CSVReader;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Paths;
public class CSV_Reader {
private static final String SAMPLE_CSV_FILE_PATH = "some_path";
public static void main(String[] args) {
try {
Reader reader = Files.newBufferedReader(Paths.get(SAMPLE_CSV_FILE_PATH));
System.out.println("before new object");
CSVReader csvReader = new CSVReader(reader);
String[] nextRecord;
System.out.println("before while");
int no_of_rows = 0;
while ( (nextRecord = csvReader.readNext()) != null ) {
no_of_rows++;
}
System.out.println("Number of lines is: " + no_of_rows );
String[] string_vector = new String[no_of_rows];
while ((nextRecord = csvReader.readNext()) != null) {
//I want to do some stuff here. It doesn't enter the loop as it is now...
}
# 1 楼答案
不确定你想做什么,但如果你真的想通过存储每一行的数据来做这件事,那么这里是你可以做的