我正在尝试编写一种方法来获取多行 csv 文件并将该文件的内容作为数组列表返回。我的问题是,当我打印数组行时,它们似乎只有文件最后一行的内容。我怀疑这可能与我不知道的 FileReader 或 BufferedReader 有关。无论如何,这是代码:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public int[][] readCSV(String pFilename) throws NumberFormatException, IOException {
int[][] arr = new int[19][19];
BufferedReader br = new BufferedReader(new FileReader(pFilename));
String line = " ";
String [] temp;
while ((line = br.readLine())!= null){
temp = line.split(","); //split spaces
for(int i = 0; i<arr.length; i++) {
for (int j = 0; j<arr.length; j++) {
arr[i][j] = Integer.parseInt(temp[j]);
}
}
}
printArray(arr);
}
public static void printArray (int[][] arr) {
for (int i =0; i <arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[i][j]);
}
System.out.println("");
}
}
}
输入
1,1,0,0,1,1,1,1,1,0,0,1,1,0,0,0,1,1,1
1,0,0,1,1,1,1 ,0,1,1,1,0,1,1,1,0,1,0,1
1,0,0,1,0,0,1,1,1,1,1,1,1, 1,1,0,1,1,0
1,1,0,1,0,1,1,0,1,0,1,0,0,1,1,1,0,1,1
1, 1,0,1,1,1,0,1,0,1,0,0,1,1,1,0,1,0,0
1,1,1,1,1,1,1,1 ,1,1,1,1,1,0,1,0,1,1,1
1,1,1,0,0,0,1,1,1,0,1,1,1,1, 1,0,1,0,1
0,1,1,1,1,1,1,1,1,1,0,0,1,1,1,0,1,1,1
1,1, 1,1,1,0,0,1,1,1,1,0,1,0,0,1,1,0,1
1,1,1,0,1,1,1,0,1 ,0,1,1,1,1,0,1,1,1,1
0,0,1,1,1,1,1,0,0,1,0,1,1,0,1, 1,0,1,0
1,0,0,0,1,1,1,1,1,1,1,1,0,1,1,1,1,0,0
1,1,1, 1,1,1,1,1,1,1,0,1,1,1,0,1,1,1,1
1,0,1,0,1,1,1,1,1,1 ,0,1,1,1,1,1,0,1,1
1,1,1,0,1,1,0,1,1,0,1,1,1,0,1,1, 0,1,0
1,0,0,1,1,1,0,1,1,1,0,1,1,1,0,0,1,1,0
1,1,1,0,1,0,1,1,1,0,1,1,1,1,1,1,1,1,1
0,1,0,0,1,1,0 ,1,0,1,1,1,0,1,1,0,1,1,1
1,1,0,0,1,1,1,1,1,1,0,0,1, 1,0,1,0,1,0
0,1,1,1,0,0,1,1,1,1,1,1,0,1,0,1,1,1,0
打印输出
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110
0111001111110101110