简体   繁体   中英

How can I store data in CSV into an array in Java?

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

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM