简体   繁体   中英

How to skip blank cells when reading a csv file in Java?

Trying to create a csv file reader, but the reader gets an ArrayIndexOutOfBoundsException when it comes across an end of line blank.

Example: Name, Email, Age, City

  1. John, johnsmith@email, 23, New York - This works and is standard
  2. John, johnsmith@email, 23, - This fails
  3. ,,23,New York - This works
  4. John, johnsmith@email,, - This fails

Any additional feedback is welcome as well!

Here's the code.

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

For the city value, just use the ternary operator to check the array length before assignment:

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

If this is not a homework project, why don't you use a library? There are several on GitHub, and here is one that seems easy to use - https://github.com/osiegmar/FastCSV .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM