我有一个 CSV 文件,我必须将其读取到 2D 字符串数组(它必须是 2D 数组)
但是它有不同的列号,例如:
One, two, three, four, five
1,2,3,4
所以我想将它们读入数组。我将其拆分,一切都很好,但我不知道如何不使用 NULL 填充缺失的列。
前面的例子是:
0: one,two,three,four,five (length 5)
1: 1,2,3,4,null (length 5)
但是我希望下一行的长度为 4,而不是没有 null 的 5。
这可能吗?
这是我到目前为止所得到的(我知道这很糟糕):
public static void read(Scanner sc) {
ArrayList<String> temp = new ArrayList<>();
while(sc.hasNextLine()) {
temp.add(sc.nextLine().replace(" ", ""));
}
String[] row = temp.get(0).split(",");
data = new String[temp.size()][row.length];
for (int i = 0; i < temp.size(); ++i) {
String[] t = temp.get(i).split(",");
for (int j = 0; j < t.length; ++j) {
data[i][j] = t[j];
}
}
}
最佳答案
听起来你想要一个非矩形的二维数组。您需要避免在二维数组上定义第二个维度。这是一个例子:
final Path path = FileSystems.getDefault().getPath("src/main/resources/csvfile");
final List<String> lines = Files.readAllLines(path);
final String[][] arrays = new String[lines.size()][];
for (int i = 0; i < lines.size(); i++) {
arrays[i] = lines.get(i).split(",");
}
所有行都被读入列表,以便我们知道二维数组的第一个维度。每行的第二个维度由拆分操作的结果确定。
关于JAVA 2D 字符串数组列数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39921090/