对于 Java 家庭作业,我需要创建一个读写 CSV 文件的类。我目前在阅读 CSV 时遇到一些问题。下面的代码只输出代码的第一行,然后生成以下错误消息:'Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at com.gc01.FileManager.CSVManager.main(CSVManager.java:27 )”。
我查看了各种示例,并且知道“opencsv”包,但我需要自己编写这段代码。我已将问题定位到语句“System.out.print(data[i]);”。但是,当交叉引用此代码时,一切似乎都很好。
我正在使用我的老师(http://www.devjavasoft.org/SecondEdition/SourceCode/Share/FileInput.java)指定的 FileInput 类中的方法。
public class CSVManager {
public static void main(String [] args){
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the file directory of the chosen CSV");
System.out.println("For Example: /Users/UserName/Downloads/FileName.csv");
///Users/ReeceAkhtar/Desktop/GeoIPCountryWhois.csv
final String fileName = sc.nextLine();
System.out.println("How many columns?");
final int columns = sc.nextInt();
BufferedReader br = null;
String line = "";
String splitBy = " , ";
try {
br = new BufferedReader(new FileReader(fileName));
while((line = br.readLine()) != null) {
for (int i = 0; i < columns; i++) {
String[] data = line.split(splitBy);
System.out.print(data[i]);
}
}
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("File Read");
}
}