java从CSV读取值时,如何将其推入二维数组?
我有一个CSV文件,包含50行和3列数字。当我从文件中读取行时,我想将它们放入一个数组中,并将该数组放入我的二维数组中。我如何做到这一点
注意事项:
- 我必须使用二维数组李>
- 我必须使用
File
、FileReader
和BufferedReader
李>
我的CSV文件如下所示:
(白天,高温,低温)
1,45,20
2,41,21
3,39,20
4,37,18
5,40,19
6,42,19
7,43,19
etc..
我希望每一行都有自己的数组。以下是我目前的代码:
public class Temps {
public static void main(String[] args) throws IOException {
File fileName = new File("DaysAndTemps.csv");
if (fileName.exists()) {
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
br = new BufferedReader(new FileReader(fileName));
System.out.println("----------------------------------------------------");
System.out.println("December 2020: Temperaturs");
System.out.println("----------------------------------------------------");
System.out.println("----------------------------------------------------");
System.out.println("Day " + "High " + "Low " + "Variance");
final int rows = 50;
final int cols = 3;
while ((line = br.readLine()) != null) {
String[][] matrix = new String[rows][cols];
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
matrix[row][col] = br.readLine();
}
}
System.out.println(Arrays.deepToString(matrix));
}
}
}
}
以下是当前的输出:
[[2,41,21, 3,39,20, 4,37,18], [5,40,19, 6,42,19, 7,43,19], [8,42,20, 9,39,19, 10,36,20], [11,35,20, 12,32,18, 13,31,16], [14,28,23, 15,35,20, 16,43,28] etc..
# 1 楼答案
试试看,我可以提出一个更简单、更全面的解决方案
只需创建一个一维数组,然后向该数组添加一个易于构建的一级降级数组
结果如下
试试看