【发布时间】:2021-05-04 01:43:55
【问题描述】:
我有一个包含 50 行和 3 列数字的 CSV 文件。当我从文件中读取行时,我想将它们放入一个数组中并将该数组推入我的二维数组中。我该如何做到这一点?
注意事项:
- 我必须使用二维数组。
- 我必须使用
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..
【问题讨论】:
标签: java arrays csv multidimensional-array bufferedreader