【问题标题】:Problems reading a CSV file in Java. Only the first line is read在 Java 中读取 CSV 文件时出现问题。只读取第一行
【发布时间】: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 循环之前进行拆分,因此您只需执行一次,而不是每列一次(在同一行数据上)。

标签: java csv file-io


【解决方案1】:

异常很清楚

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 

意味着,您正在尝试访问数组中不存在的第一个元素

既然您说System.out.print(data[i]); 是发生异常的行,那么对于第一行data 必须只填充了单个元素

使用 IDE 调试问题,找出 split 方法导致意外元素的原因。我怀疑在, 周围使用空格是" , " 中的原因

【讨论】:

    【解决方案2】:

    试试这个。如果你把 for 循环拆分出来,一切都会好起来的。

    String[] data = line.split(splitBy);
    while((line = br.readLine()) != null){
        for (int i = 0; i < columns; i++){
            System.out.print(data[i]);
        }
    }
    

    【讨论】:

      【解决方案3】:
       while((line = br.readLine()) != null){
          for (int i = 0; i < columns; i++){
          String[] data = line.split(splitBy);
          System.out.print(data[i]);
          }
      
      1. 您在for 循环内多次拆分一行,没有任何理由。
      2. 您正在使用" , " 进行拆分(这可能是您遇到ArrayIndexOfBound 异常的原因)而不是使用",";如果您愿意,请在 data[i] 上使用 trim() 以消除尾随/前导空格。
      3. 拆分后,检查data.length 是否等于columns 以确保一致性。
      4. 我们现在处于 JDK 7 时代,我们可以使用 try-with-resource 关闭 try(){} 上下文中声明的资源,从而让我们摆脱 finally

      所以你的可能应该如下所示:

        try (BufferedReader br = new BufferedReader(new FileReader(fileName))){
           while((line = br.readLine()) != null){
              String[] data = line.split(splitBy);
      
              if(data.length != columns)continue; // check for consistency, 
                                             //might throw an exception 
      
              for (int i = 0; i < columns; i++){
                System.out.print(data[i].trim());
              }
      
        }catch(IoExection ex)
        {
           ex.printStackTrace();  
        }
      

      【讨论】:

        猜你喜欢
        • 2014-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-28
        • 2018-02-28
        相关资源
        最近更新 更多