Mila1611
Mila1611

Reputation: 71

Java Stream to String[] Array

I'm reading from a CSV file with a structure like this:

1;Miller Hame; 1,2,3,4,5.....; 1232323;

I have to split it to String[], I could work with every line and there with every "Part"

My Code so far:

Stream<String> input = java.nio.file.Files.lines(java.nio.file.Paths.get("data.csv"));

String[] lines = input.skip(1)
        .map(s->s.split(";"))
        .toArray(String[]::new);

Actually I'm getting java.lang.ArrayStoreException.

(Yes, it's for homework, but I don't want the whole solution, only for this very small part of the work.)

Upvotes: 2

Views: 4723

Answers (1)

djm.im
djm.im

Reputation: 3323

Something like this

Stream<String> input = Files.lines(Paths.get("src/data.csv"));

String[][] lines = input.skip(1)
        .map(s -> s.split(";"))
        .toArray(String[][]::new);

Advice: You don't have to type full path for a class. You can import it. This is for Files and Paths classes

import java.nio.file.Files;
import java.nio.file.Paths;

Upvotes: 6

Related Questions