除非删除特定列,否则无法从CSV文件中读取文本



我需要从Java中的CSV文件中读取信息,并将信息添加到字符串数组列表中。问题是代码在读取CSV文件时出现错误,但如果我去掉名为"的CSV列;"概要";,代码运行良好。很明显,这个专栏与代码失败有关,但我不知道是什么。有人有什么想法吗?

链接到CSV的谷歌表单版本https://docs.google.com/spreadsheets/d/1EO243KiaZ_uxEKF1mvozONHvTBm5HfFsUvrR5SSB238/edit?usp=sharing

此处编码-->

package testerproject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class testerpage {
private List<String[]> list = new ArrayList();
testerpage(){
try {
animeList();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
private void  animeList() throws IOException {
File file = new File("resources/CSVFiles/animeProjectData.csv");
int count = 0; //keep track of where in the list new line is added
try{
BufferedReader br = new BufferedReader(new FileReader(file));
String line = "";
//add line from CSV file to specified list index
while ((line = br.readLine()) != null) {
list.add(count,line.split(",")); 
count++;
}
} catch (FileNotFoundException e) {
}           
System.out.println(list.get(2)[3]);
}
}

给出的错误->

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 1
at testerproject.testerpage.animeList(testerpage.java:37)
at testerproject.testerpage.<init>(testerpage.java:17)
at testerproject.tester.main(tester.java:6)

使用opencsv读取csv文件,我尝试了您共享的csv文件。使用opencsw能够读取它,没有任何错误,更多参考https://www.baeldung.com/opencsv

import com.opencsv.CSVReader;
public class testerpage {
private List<String[]> list = new ArrayList();
testerpage(){
try {
animeList();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
private void  animeList() throws IOException {
File file = new File("resources/CSVFiles/animeProjectData.csv");
int count = 0; //keep track of where in the list new line is added
try{
Reader reader = Files.newBufferedReader(file.toPath());
CSVReader csvReader = new CSVReader(reader);
String[] line;
while ((line = csvReader.readNext()) != null) {
list.add(line);
count++;
}
reader.close();
csvReader.close();
} catch (FileNotFoundException e) {
}           
System.out.println(list.get(2)[3]);
}
}

您的代码很好,我相信问题出现在您在此处共享的电子表格中C:3[2][3]处的逗号中

.
.
.
when he meets a beautiful violinist, Kaori Miyazono, who stirs up his 

world and sets him on a journey to face music again. 

Based on the manga series of the same name,  Shigatsu wa Kimi no 

Uso  approaches the story of Kousei's recovery as he discovers that 
.
.
.

此文件不能用逗号分隔。我建议将工作表转换为TSV(制表符分隔(或其他分隔符,而不是逗号,可能类似于条形符号|?,因为你在列的内容中使用了逗号。

相关内容

  • 没有找到相关文章

最新更新