Reputation: 595
I have the following .csv file:
B00987,58
B00567,43
B00343,59
B00653,25
B00757,31
B00876,40
B00421,62
B00568,78
B00826,79
B00126,93
B00862,62
B00999,12
B00237,68
B00762,85
B00864,49
I need to store all the B00000 numbers in an array to use later. The array should look like:
Position 0 | B00987
Position 1 | B00567
Position 2 | B00343
Position 3 | B00653
....
Position 13 | B00762
Position 14 | B00864
The file path is:
String filepath = "src\\marks.csv";
Any idea how to do this in java? Thanks
Upvotes: 1
Views: 254
Reputation: 11032
You can use Java Streams with the Files.lines()
method:
try (Stream<String> lines = Files.lines(Paths.get("marks.csv"))) {
String[] result = lines
.map(line -> line.split(","))
.map(items -> items[0])
.toArray(String[]::new);
} catch (IOException e) {
e.printStackTrace();
}
This reads all lines to a stream, splits each line by ,
and uses only the first element.
Upvotes: 3
Reputation: 44932
You are only storing the first column with a predictable format so you can look for the first occurrence of the ,
delimiter in each line. Assuming marks.csv
is a resource in your JAR:
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
getClass().getResourceAsStream("/marks.csv")))) {
String[] numbers = reader.lines()
.map(l -> l.substring(0, l.indexOf(',')))
.toArray(String[]::new);
}
Upvotes: 1