[英]JAVA 2D String array column numbers
I have a CSV file which I have to read to a 2D string array (it must be a 2D array) 我有一个CSV文件,必须将其读取到2D字符串数组(它必须是2D数组)
However it has different column number, like: 但是,它具有不同的列号,例如:
One, two, three, four, five
一二三四五
1,2,3,4
1,2,3,4
So I want to read those into an array. 所以我想将它们读入数组。 I split it everything is good, however I don't know how not to fill the missing columns with NULLs.
我将其拆分为一切都很好,但是我不知道如何不用NULL填充缺失的列。
The previous example is: 上一个示例是:
0: one,two,three,four,five (length 5)
0:一,二,三,四,五(长度5)
1: 1,2,3,4,null (length 5)
1:1,2,3,4,null(长度5)
However I want the next row's length to be 4 and not 5 without null. 但是我希望下一行的长度是4,而不是5,不为null。
Is this possible? 这可能吗?
This is where I've got so far (I know it's bad): 这是到目前为止我所知道的(我知道这很糟糕):
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];
}
}
}
Sounds like you want a non-rectangular 2-dimensional array. 听起来好像您想要一个非矩形的二维数组。 You'll want to avoid defining the second dimension on your 2D array.
您将要避免在2D数组上定义第二维。 Here's an example:
这是一个例子:
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(",");
}
All lines are read into a List so that we know the first dimension of the 2D array. 将所有行读入一个列表,以便我们知道2D数组的第一维。 The second dimension for each row is determined by the result of the split operation.
每行的第二维由拆分操作的结果确定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.