【发布时间】:2013-10-25 10:45:08
【问题描述】:
对于 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");
}
}
【问题讨论】:
-
大概该行实际上包含的列数与用户指定的一样多。请注意,您应该 在
for循环之前进行拆分,因此您只需执行一次,而不是每列一次(在同一行数据上)。