Read a whole CSV file into objects
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Reading a CSV file into objects is three steps: read the lines, skip the header, and turn each remaining line into a record with a method like Student.fromCsv. The result is a List<Student> or a Map that the rest of your program can search, sort and total.
Files.lines with skip and map
Files.lines(path, StandardCharsets.UTF_8) returns a Stream<String> with one item per line of the file. Add skip(1) to drop the header and map(Student::fromCsv) to turn each line into a record, then toList() to collect them.
Example 1 · Files.lines, skip(1) and map
import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.util.List;import java.util.stream.Stream;
record Student(int roll, String name, int marks) { static Student fromCsv(String line) { String[] f = line.split(",", -1); if (f.length != 3) { throw new IllegalArgumentException("Expected 3 fields but got " + f.length + ": " + line); } return new Student(Integer.parseInt(f[0].trim()), f[1].trim(), Integer.parseInt(f[2].trim())); }}
public class ReadCsvDemo { public static void main(String[] args) throws IOException { Path file = Path.of("marks.csv"); Files.writeString(file, """ roll,name,marks 101,Asha Rao,87 102,Bhavesh Patel,64 103,Chitra Iyer,92 """, StandardCharsets.UTF_8);
List<Student> students; try (Stream<String> lines = Files.lines(file, StandardCharsets.UTF_8)) { students = lines.skip(1) .map(Student::fromCsv) .toList(); }
System.out.println("Loaded " + students.size() + " students from " + file.getFileName()); int total = 0; for (Student s : students) { System.out.println(s.roll() + " " + s.name() + " " + s.marks()); total += s.marks(); } System.out.println("Class average: " + (total / students.size()));
Files.deleteIfExists(file); }}Loaded 3 students from marks.csv 101 Asha Rao 87 102 Bhavesh Patel 64 103 Chitra Iyer 92 Class average: 81
What this code does
- The program first writes a small
marks.csvin the working folder, so it runs anywhere, and deletes it at the end. In a real program the file already exists. skip(1)drops the header,map(Student::fromCsv)parses each line, andtoList()(Java 16) collects the records. The try-with-resources block closes the file as soon as the list is built.
The stream keeps the file open until it is closed, so always create it inside try-with-resources. The file is read lazily, line by line, so this works for big files too. Files.lines understands both Windows (\r\n) and Linux (\n) line endings, so you do not see a stray \r at the end of each line.
StandardCharsets.UTF_8. Since Java 18 it is the default anyway, but on Java 17 the default depends on the computer, and names with accents or the rupee sign can turn into junk.Empty and blank lines
A blank line is a line that is empty or holds only spaces. Many files end with one, and people add them between groups of rows when they edit by hand.
Example 2 · Blank lines break the import, isBlank fixes it
import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.util.List;import java.util.stream.Stream;
record Student(int roll, String name, int marks) { static Student fromCsv(String line) { String[] f = line.split(",", -1); if (f.length != 3) { throw new IllegalArgumentException("Expected 3 fields but got " + f.length + ": '" + line + "'"); } return new Student(Integer.parseInt(f[0].trim()), f[1].trim(), Integer.parseInt(f[2].trim())); }}
public class BlankLinesDemo { static List<Student> load(Path file, boolean skipBlank) throws IOException { try (Stream<String> lines = Files.lines(file, StandardCharsets.UTF_8)) { return lines.skip(1) .filter(line -> !skipBlank || !line.isBlank()) .map(Student::fromCsv) .toList(); } }
public static void main(String[] args) throws IOException { Path file = Path.of("hostel.csv"); Files.writeString(file, "roll,name,marks\n101,Asha,87\n\n102,Bhavesh,64\n \n", StandardCharsets.UTF_8);
try { load(file, false); } catch (IllegalArgumentException e) { System.out.println("Without filter: " + e.getMessage()); } List<Student> students = load(file, true); System.out.println("With filter: " + students.size() + " students"); students.forEach(System.out::println);
Files.deleteIfExists(file); }}Without filter: Expected 3 fields but got 1: '' With filter: 2 students Student[roll=101, name=Asha, marks=87] Student[roll=102, name=Bhavesh, marks=64]
What this code does
- The file has an empty line in the middle and a line of spaces at the end. Without the filter, the empty line reaches
fromCsv, which finds only 1 field and throws. filter(line -> !line.isBlank())drops both the empty line and the line of spaces, so the two real rows load cleanly.
A blank line has no commas, so fromCsv("") gets 1 field instead of 3 and throws. Filter them out before parsing: filter(line -> !line.isBlank()). isBlank() (Java 11) is true for "" and for " ". Do not filter too much. A line like ,, is not blank: it is a row with every field empty, and it should reach your checks so that it can be reported.
Keeping line numbers with a loop
A message like Bad row: 10x is much less useful than marks.csv line 4: Bad marks '10x'. To print it, you need to know which line of the file you are on, and a stream does not tell you.
Example 3 · A BufferedReader loop that reports the line number
import java.io.BufferedReader;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.List;
record Student(int roll, String name, int marks) { static Student fromCsv(String line) { String[] f = line.split(",", -1); if (f.length != 3) { throw new IllegalArgumentException("expected 3 fields but got " + f.length); } return new Student(Integer.parseInt(f[0].trim()), f[1].trim(), Integer.parseInt(f[2].trim())); }}
public class LineNumberDemo { static List<Student> load(Path file) throws IOException { List<Student> students = new ArrayList<>(); try (BufferedReader in = Files.newBufferedReader(file, StandardCharsets.UTF_8)) { String line = in.readLine(); // header int lineNo = 1; while ((line = in.readLine()) != null) { lineNo++; if (line.isBlank()) { continue; } try { students.add(Student.fromCsv(line)); } catch (IllegalArgumentException e) { throw new IllegalArgumentException( file.getFileName() + " line " + lineNo + ": " + e.getMessage(), e); } } } return students; }
public static void main(String[] args) throws IOException { Path file = Path.of("marks.csv"); Files.writeString(file, "roll,name,marks\n101,Asha,87\n\n102,Bhavesh,10x\n103,Chitra,92\n", StandardCharsets.UTF_8); try { load(file); } catch (IllegalArgumentException e) { System.out.println("Import failed: " + e.getMessage()); System.out.println("Cause: " + e.getCause().getClass().getSimpleName()); } Files.deleteIfExists(file); }}Import failed: marks.csv line 4: For input string: "10x" Cause: NumberFormatException
What this code does
lineNogoes up for every line read, blank ones included, soline 4is exactly where a text editor shows the bad row102,Bhavesh,10x.NumberFormatExceptionis a subclass ofIllegalArgumentException, so one catch handles both a bad number and a wrong field count. The new exception keeps the original as its cause.
A plain loop does. Open the file with Files.newBufferedReader(path, UTF_8), call readLine() until it returns null, and add 1 to a counter for every line read, including the header and blank lines. The counter then matches the line number shown in any text editor. Catch the parse exception inside the loop and throw a new one that adds the file name and line number, with the original exception as its cause. The Skip and report bad rows lesson goes further and keeps going after a bad row.
Collecting into a list or map
A List keeps the rows in file order and is right when you will go through all of them, for example to total the fees.
Example 4 · toMap for lookups, and the duplicate key it finds
import java.util.List;import java.util.Map;import java.util.stream.Collectors;
record Student(int roll, String name, int marks) { static Student fromCsv(String line) { String[] f = line.split(",", -1); return new Student(Integer.parseInt(f[0].trim()), f[1].trim(), Integer.parseInt(f[2].trim())); }}
public class ToMapDemo { static Map<Integer, Student> byRoll(List<String> lines) { return lines.stream() .skip(1) .map(Student::fromCsv) .collect(Collectors.toMap(Student::roll, s -> s)); }
public static void main(String[] args) { List<String> good = List.of("roll,name,marks", "101,Asha,87", "102,Bhavesh,64", "103,Chitra,92"); Map<Integer, Student> map = byRoll(good); System.out.println("Roll 102: " + map.get(102).name()); System.out.println("Roll 150: " + map.get(150));
List<String> withDuplicate = List.of("roll,name,marks", "101,Asha,87", "102,Bhavesh,64", "102,Dev,71"); try { byRoll(withDuplicate); } catch (IllegalStateException e) { System.out.println(e.getMessage()); } }}Roll 102: Bhavesh Roll 150: null Duplicate key 102 (attempted merging values Student[roll=102, name=Bhavesh, marks=64] and Student[roll=102, name=Dev, marks=71])
What this code does
- With a map, finding a student by roll number is one
getcall instead of a loop over the list. A missing roll givesnull. - Two rows share roll 102, so
toMapthrowsIllegalStateExceptionand names both records. A list would have kept both rows silently.
Example 5 · groupingBy: fest registrations per event
import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.stream.Collectors;import java.util.stream.Stream;
record Registration(String name, String college, String event) { static Registration fromCsv(String line) { String[] f = line.split(",", -1); return new Registration(f[0].trim(), f[1].trim(), f[2].trim()); }}
public class FestDemo { public static void main(String[] args) throws IOException { Path file = Path.of("fest.csv"); Files.writeString(file, """ name,college,event Asha,VIT,Coding Bhavesh,NIT Trichy,Dance Chitra,VIT,Quiz Dev,IIT Bombay,Coding
Esha,NIT Trichy,Coding """, StandardCharsets.UTF_8);
List<Registration> regs; try (Stream<String> lines = Files.lines(file, StandardCharsets.UTF_8)) { regs = lines.skip(1).filter(l -> !l.isBlank()).map(Registration::fromCsv).toList(); }
Map<String, Long> perEvent = regs.stream() .collect(Collectors.groupingBy(Registration::event, TreeMap::new, Collectors.counting())); System.out.println("Per event: " + perEvent);
Map<String, List<String>> namesByCollege = regs.stream() .collect(Collectors.groupingBy(Registration::college, TreeMap::new, Collectors.mapping(Registration::name, Collectors.toList()))); namesByCollege.forEach((college, names) -> System.out.println(college + " -> " + names));
Files.deleteIfExists(file); }}Per event: {Coding=3, Dance=1, Quiz=1}
IIT Bombay -> [Dev]
NIT Trichy -> [Bhavesh, Esha]
VIT -> [Asha, Chitra]What this code does
- One pass reads the file into records. After that, the file is closed and everything else works on the list in memory.
groupingBywithTreeMap::newgives sorted keys, so the output order is the same on every run.counting()counts rows per event;mapping(..., toList())collects names per college.
A Map is right when you look rows up by a key, such as a roll number or PNR. Collectors.toMap(Student::roll, s -> s) builds one in a single step. If two rows have the same key, it throws IllegalStateException: Duplicate key. That is useful: it finds duplicate roll numbers in the file. To count or group rows, use Collectors.groupingBy, for example rows per city or the list of students per section. Pass TreeMap::new when you want the keys sorted.
Next step
Check your understanding
12 quick questions