我正在使用 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/