我正在使用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++;
}
但是,我得到一个空指针异常。我应该做什么的想法?
P.S。是的,此代码被try / catch语句包围。
答案 0 :(得分:3)
问题是,一旦你完成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]
答案 1 :(得分:2)
而不是数组使用像List一样动态的东西。例如:
List<String[]> data = new ArrayList<String[]>();
同样使用String的split()
方法将简化行的加载。
答案 2 :(得分:1)
你的问题是BufferedReaders通过读取工作直到文件结束,然后它们卡在那里。您的代码需要两次读取文件,但由于您已经达到了EOF,因此BufferedReader卡住了返回null。我倾向于通过将行填充到ArrayList中来解决这个问题,并使用size()方法来获取行数。源代码看起来像这样:
int rowsInFile=0;
ArrayList<String> lines = new ArrayList<String>();
String tmp = "";
while(tmp=bugRdr.readLine())
{
lines.add(tmp);
}
rowsInFile = lines.size();
String[][] numbers = new String[rowsInFile][16];
int row = 0;
for(String line : lines)
{
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++;
}