从CSV中读取值时,如何将其推入二维数组?



我有一个包含50行和3列数字的CSV文件。当我从文件中读取行时,我希望将它们放入一个数组中,并将该数组推入我的二维数组中。我该如何做到这一点?

事项:

  • 我必须使用二维数组
  • 我必须使用File,FileReaderBufferedReader

我的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.. 

将while循环改为this

String[][] matrix = new String[rows][cols];
int row = 0;
while ((line = br.readLine()) != null) {
if (line.isEmpty()) {
continue;
}
String[] items = line.split(",");
for (int col = 0; col < cols; col++) {
matrix[row][col] = items[col];
}
row++;
}

我可以建议一个更简单、更全面的解决方案。

只是创建一个一维数组,然后在该数组中添加一个易于构造的一维数组。

File fileName = new File("C:\descktop\Portfolio" +
"\testFrorAnswers\src\com\company\res.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) {
Object[] a = new Object[50];
for (int row = 0; row < rows; row++) {
String[] array = br.readLine().split(",");
a[row] = array;
}
System.out.println(Arrays.deepToString(a));
}
}

结果如下

[2, 41, 21], [3, 39, 20], [4, 37, 18], [5, 40, 19], [6, 42, 19], [7, 43, 19], etc...

试一试

最新更新