How to read a CSV file in Java?

To read a CSV file in Java, use Scanner and String.split.

Here's how you do it:

# companies.csv
Apple,AAPL,1976
Amazon,AMZN,1994
Google,GOOG,1998
var companies = new ArrayList<>();
var csv = new java.io.File("companies.csv");

try (var scanner = new java.util.Scanner(csv)) {
  while (scanner.hasNextLine()) {
    companies.add(java.util.Arrays.asList(scanner.nextLine().split(",")));
  }
} catch (FileNotFoundException e) {
  e.printStackTrace();
}

// [[Apple, AAPL, 1976], [Amazon, AMZN, 1994], [Google, GOOG, 1998]]
System.out.println(companies);