java - 将 CSV 文件导入二维字符串数组

标签 java arrays csv

我必须将文本文件读入二维数组。

我遇到的唯一问题是数组的宽度各不相同,最大为 9 列。 不知道会有多少行。

例如,有些行有 6 列,有些有 9 列。

这是我的 CSV 文件的一小部分:

1908,Souths,Easts,Souths,Cumberland,Y,14,12,4000
1909,Souths,Balmain,Souths,Wests,N
1910,Newtown,Souths,Newtown,Wests,Y,4,4,14000
1911,Easts,Glebe,Glebe,Balmain,Y,11,8,20000
1912,Easts,Glebe,Easts,Wests,N
1913,Easts,Newtown,Easts,Wests,N

这是我到目前为止的代码

    import java.io.*;
import java.util.*;

public class ass2 {

    public static void main(String[] args) throws IOException {
        readData();

    }

    public static void readData() throws IOException{
        BufferedReader dataBR = new BufferedReader(new FileReader(new File("nrldata.txt")));
        String line = "";

        ArrayList<String[]> dataArr = new ArrayList<String[]>(); //An ArrayList is used because I don't know how many records are in the file.

        while ((line = dataBR.readLine()) != null) { // Read a single line from the file until there are no more lines to read

            String[] club = new String[9]; // Each club has 3 fields, so we need room for the 3 tokens.

            for (int i = 0; i < 9; i++) { // For each token in the line that we've read:
                String[] value = line.split(",", 9);                
                club[i] = value[i]; // Place the token into the 'i'th "column"
            }

            dataArr.add(club); // Add the "club" info to the list of clubs.
        }

        for (int i = 0; i < dataArr.size(); i++) {
            for (int x = 0; x < dataArr.get(i).length; x++) {
                System.out.printf("dataArr[%d][%d]: ", i, x);
                System.out.println(dataArr.get(i)[x]);
            }
        }
    }

我得到的错误是:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at ass2.readData(ass2.java:23)
at ass2.main(ass2.java:7)

有人可以帮忙吗:'(

谢谢!

最佳答案

您可以使用 OpenCSV用于读取 CSV 文件。

// Read all
CSVReader csvReader = new CSVReader(new FileReader(new File("nrldata.txt")));
List<String[]> list = csvReader.readAll();

// Convert to 2D array
String[][] dataArr = new String[list.size()][];
dataArr = list.toArray(dataArr);

关于java - 将 CSV 文件导入二维字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16784014/

相关文章:

python - 如何删除 CSV 文件中某个值大于另一个值的所有行?

java - 没有 Spring Boot 可以使用 Spring Cloud Zuul 吗?

java - 如何使用多线程使我的应用程序更快

java - 使用 Java JOptionPane 将十进制转换为二进制

javascript - 根据选择显示隐藏选择框和选择框选项

php - 遍历多维数组

php - 使用 php 将包含多字节内容(阿拉伯语和日语)的 csv 导入到 mysql 表中

java - 通过其连接的适配器调用 Activity 的方法对应用程序的面向对象设计有何影响?

javascript - 根据参数更新数组中的值

excel - 保存导入/导出规范 '' 时出错