1

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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.