java - 使用 BufferedReader 对多维数组中的行进行计数

标签 java file-io multidimensional-array bufferedreader

我正在使用 BufferedReader 读取 .csv 文件。读取文件和提取数据没有问题。但是,我确实遇到的问题是我必须对数组声明进行硬编码。例如:

        String[][] numbers=new String[5258][16];

我使用的 .csv 文件有 5258 行和 16 列。不过,我希望能够做这样的事情:

        String[][] numbers=new String[rowsInFile][16];

换句话说,我希望变量“rowsInFile”等于文件中的行数(我不想计算列数,因为我将通过此程序运行的每个 .csv 文件都有 16列)。

这是我目前的代码:

        int row = 0;
        int col = 0;

        String fileInput = JOptionPane.showInputDialog(null, 
                "Please enter the path of the CSV file to read:");

        File file = new File(fileInput);

        BufferedReader bufRdr;
        bufRdr = new BufferedReader(new FileReader(file));
        String line = null;

        //get rows in the file
        int rowsInFile = 0;
        while(bufRdr.readLine() != null) {
            rowsInFile++;
            row++;
        }
        String[][] numbers=new String[rowsInFile][16];

        //read each line of text file
        row = 0;
        while((line = bufRdr.readLine()) != null) {
            StringTokenizer st = new StringTokenizer(line,",");
            col=0;

            while (st.hasMoreTokens()) {
                //get next token and store it in the array
                numbers[row][col] = st.nextToken();
                col++;
            }
            row++;
        }

但是,我得到一个空指针异常。我应该做什么有什么想法吗?

附言是的,这段代码被 try/catch 语句包围。

最佳答案

问题是,一旦你通过 BufferedReader曾经,你不能再回到过去。换句话说,你必须使用一个新的 BufferedReader .

bufRdr = new BufferedReader(new FileReader(file));
row = 0;
while((line = bufRdr.readLine()) != null) {

或者,您可以使用像 ArrayList<String[]> 这样的动态数组结构或 LinkedList<String[]>存储行。

LinkedList<String[]> numbers = new LinkedList<String[]>();

while( (line = bufRdr.readLine()) != null ) {
    numbers.add(line.split(","));
}

然后而不是做 numbers[i][j] , 你使用 numbers.get(i)[j] .

关于java - 使用 BufferedReader 对多维数组中的行进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6982930/

相关文章:

C++ 可能的内存泄漏读取文件

ios - 保证 iOS 何时写入 Documents 目录中的文件?

python - 如何将值作为索引的函数赋值给 numpy 数组?

java - Java 中的应用程序范围的方法拦截器

java - 实现一个链表栈和队列,不知道自己设置的代码是否足够高效

c++ - _SH_SECURE 和 _SH_DENYWR 有什么区别

google-apps-script - 返回二维数组的特定行并写入 Range

java - 使用服务器缓存 15 分钟

java - Java 中 equals() 方法的行为

在 C 中创建字符串值并将其添加到二维数组