Corner Corner - 1 year ago 82
Java Question

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)

However it has different column number, like:


One, two, three, four, five

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.

The previous example is:


0: one,two,three,four,five (length 5)

1: 1,2,3,4,null (length 5)


However I want the next row's length to be 4 and not 5 without 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];
}
}
}

Answer Source

Sounds like you want a non-rectangular 2-dimensional array. You'll want to avoid defining the second dimension on your 2D array. 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. The second dimension for each row is determined by the result of the split operation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download