[英]Why does Scanner read every other line of CSV file? Java
我正在读取CSV文件,并将每个定界元素放入二维数组中。 代码如下:
public DataProcess(String filename, String[][] contents, int n) {//n is 6 for contents, 5 for fiveMinContents
Scanner fileReader = null;
try {
fileReader = new Scanner(new File(filename));
} catch (FileNotFoundException ex) {
System.out.println(ex + " FILE NOT FOUND ");
}
fileReader.useDelimiter(",");
int rowIndex = 0;
while (fileReader.hasNext()) {
for (int j = 0; j < n; j++) {
contents[rowIndex][j] = fileReader.next();
System.out.println("At (" + rowIndex +", "+j+"): " +
contents[rowIndex][j]);
}
rowIndex++;
fileReader.nextLine();
}
}
我不确定为什么它会读取此特定CSV文件的其他所有行,因为这是以这种方式读取的文件2/2。 第一个没问题,但是现在这个跳过了其他每一行。 为什么它对一个有效,但对另一个无效? 我正在Eclipse的最新更新上运行它。
我也签出了这个答案,它没有帮助。
因为循环的最后一行将读取并丢弃该行。 您需要类似的东西,
while (fileReader.hasNextLine()) {
String line = fileReader.nextLine();
contents[rowIndex] = fileReader.split(",\\s*");
System.out.println("At (" + rowIndex + "): "
+ Arrays.toString(contents[rowIndex]));
rowIndex++;
}
您也可以通过一个调用来打印多维数组,例如
System.out.println(Arrays.deepToString(contents));
尽管该方法可能对您有用,但这并不是最佳选择。 有用于Java的预制CSV阅读器。 一个例子是commons-csv :
Reader in = new FileReader("path/to/file.csv");
Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
for (CSVRecord record : records) {
String date = record.get(1);
String time = record.get(2);
// and so on, so forth
}
在类路径上必须有少量依赖项 。 希望能有所帮助。
我找到了这个问题的问题。
首先,我建议使用建议的外部库。
问题在于,由于第二个文件正在读取整行,而第一个CSV文件正在读取我想要的内容,但是文件末尾有一列我忽略了。 一定有一种结构化CSV文件的方式,其中行的末尾具有不同的分隔符或沿这些行的内容-不确定。 为了解决这个问题,我刚刚在第二个文件中添加了一个额外的列,但我没有读进去。 它就在那里。
简而言之,请使用外部CSV阅读器库。 如果您不想这样做,则只需在文件中的最后一列之后直接添加一列,而不读取它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.