【问题标题】:How to skip blank cells when reading a csv file in Java?在 Java 中读取 csv 文件时如何跳过空白单元格?
【发布时间】:2020-08-07 00:35:09
【问题描述】:

尝试创建 csv 文件阅读器,但阅读器遇到行尾空白时会收到 ArrayIndexOutOfBoundsException。

示例:姓名、电子邮件、年龄、城市

  1. John,johnsmith@email,23 岁,纽约 - 这是可行的并且是标准的
  2. 约翰,johnsmith@email,23 岁, - 失败
  3. ,,23,New York - 这工作
  4. 约翰,johnsmith@email,- 失败

也欢迎任何其他反馈!

这是代码。

    public class Main {
    static String filepath = "filepath.csv";

    public static void main(String[] args) {
        SQLiteDB db = new SQLiteDB();
        CSVReader(filepath);        
    }

    public static void CSVReader(String filepath) {
        List<User> users = new ArrayList<User>();
        BufferedReader br = null;
        String line;
        int count = 1;

        try {
            br = new BufferedReader(new FileReader(filepath));
            while ((line = br.readLine()) != null) {
                if(line.trim().length() > 0) {
                User user = new User();
                String[] userinfo = line.split(",(?=([^\"]|\"[^\"]*\")*$)");
                user.firstName = userinfo[0];
                user.lastName = userinfo[1];
                user.email = userinfo[2];
                user.gender = userinfo[3];
                user.image = userinfo[4];
                user.bank = userinfo[5];
                user.transaction = userinfo[6];
                user.bool1 = userinfo[7];
                user.bool2 = userinfo[8];
                user.city = userinfo[9];
                users.add(user);
                
                System.out.println("Count:" + count + " " + user.getBool2());
                count++;
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ArrayIndexOutOfBoundsException e) {
            e.printStackTrace();
        }
    }
}

【问题讨论】:

  • 所以只有userinfo[9] 是个问题?如果找不到,值应该是多少?
  • 也许可以尝试一下来检测ArrayIndexOutOfBoundsException?

标签: java csv filereader


【解决方案1】:

对于城市值,赋值前只需使用三元运算符检查数组长度即可:

user.city = userinfo.length == 10 ? userinfo[9] : "";

【讨论】:

    【解决方案2】:

    如果这不是一个家庭作业项目,你为什么不使用图书馆? GitHub上有好几个,这里有一个看起来好用的——https://github.com/osiegmar/FastCSV。

    【讨论】:

      猜你喜欢
      • 2013-09-24
      • 2018-07-10
      • 2020-05-31
      • 1970-01-01
      • 2020-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多