【问题标题】:Difficulty reading csv in java; using eclipse在 java 中读取 csv 有困难;使用日食
【发布时间】:2016-02-16 17:09:17
【问题描述】:

我正在学习 AP CompSci A,我们正在处理一个包含 .csv 文件的项目。

目前,我正在尝试在 java 中解析/读取一个 .csv 文件(包含字符的十六进制代码),以便最终可以在用户提示时编写一个小程序将字符转换为十六进制定义。 下面是我试图用来读取 .csv 文件的代码。

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;




public class showfont {


public static void main ( String [] args) {

    showfont obj = new showfont();
    obj.run();

}

public void run() {

    String csvFile = "/Users/rmollo/Desktop/entityfacts.csv";
    BufferedReader br = null;
    String line = "";
    String cvsSplitBy = ",";

    try {

        br = new BufferedReader(new FileReader(csvFile));
        while ((line = br.readLine()) != null) {
            String[] answer = line.split(cvsSplitBy);

            System.out.println("test [hex=  " + answer[2]
                    + " "
                    + ", description=" +answer[5] + "]");

}
    } 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("Done");
}
}

当我运行它时,我收到以下错误消息:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at showfont.run(showfont.java:37)
at showfont.main(showfont.java:20)

我确信这是一个措辞糟糕的问题(这是我的第一个问题),但如果有人可以向我解释这些错误的含义/我如何解决它们,那将不胜感激!

谢谢!

【问题讨论】:

  • 您的异常意味着有一行少于 3 个“单元格”。
  • 您真的应该只搜索错误,以便努力了解错误是什么、为什么会发生以及如何解决它。
  • 某些数组位置不存在。测试你的大小数组。

标签: java eclipse csv


【解决方案1】:

在你的拆分下添加这个:

if (answer.length < 6) { System.out.println("Line "+line+" is too short"); continue; }

并检查它是否打印任何内容。

【讨论】:

    【解决方案2】:

    问题似乎出在以下行:

    System.out.println("test [hex=  " + answer[2]
                    + " "
                    + ", description=" +answer[5] + "]");
    

    您的索引超出范围。

    【讨论】:

      【解决方案3】:

      如果文件是这个(https://wush.net/svn/mindprod/com/mindprod/entities/entityfacts.csv),你必须跳过没有逗号的注释行

      if(!line.startsWith("#")){
      
          //split code
          ...
      

      添加更多控件以跳过“不常见”行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-27
        • 1970-01-01
        • 1970-01-01
        • 2013-07-03
        • 1970-01-01
        • 1970-01-01
        • 2012-03-06
        • 2018-07-29
        相关资源
        最近更新 更多