【发布时间】:2011-10-22 09:55:51
【问题描述】:
我正在使用 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 语句包围。
【问题讨论】:
-
哪一行抛出了 NPE,您发布的代码中没有任何可疑之处。
-
很抱歉听起来很新手,但实际上我什至不知道如何检查。如果我单击显示的错误,它只会弹出一个名为“为 java.lang.NullPointerException 创建断点”的新窗口。
标签: java file-io multidimensional-array bufferedreader