javabeginner

CSV Parser — Read and Write CSV Files

Parse and write CSV files in Java without external libraries using BufferedReader and String operations.

java
import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.stream.*;

public class CsvParser {

    // Read CSV to list of maps (header → value)
    public static List<Map<String, String>> readCsv(String path) throws IOException {
        try (var reader = Files.newBufferedReader(Path.of(path))) {
            String headerLine = reader.readLine();
            if (headerLine == null) return List.of();
            String[] headers = headerLine.split(",");

            return reader.lines()
                .map(line -> parseLine(line, headers))
                .toList();
        }
    }

    private static Map<String, String> parseLine(String line, String[] headers) {
        String[] values = line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);
        Map<String, String> row = new LinkedHashMap<>();
        for (int i = 0; i < headers.length && i < values.length; i++) {
            row.put(headers[i].trim(), values[i].trim().replaceAll("^\"|\"$", ""));
        }
        return row;
    }

    // Read CSV to records
    record Person(String name, int age, String city) {}

    public static List<Person> readPeople(String path) throws IOException {
        return readCsv(path).stream()
            .map(row -> new Person(
                row.get("name"),
                Integer.parseInt(row.getOrDefault("age", "0")),
                row.get("city")
            ))
            .toList();
    }

    // Write CSV
    public static void writeCsv(String path, List<String> headers,
                                 List<List<String>> rows) throws IOException {
        try (var writer = Files.newBufferedWriter(Path.of(path))) {
            writer.write(String.join(",", headers));
            writer.newLine();
            for (var row : rows) {
                String line = row.stream()
                    .map(val -> val.contains(",") ? "\"" + val + "\"" : val)
                    .collect(Collectors.joining(","));
                writer.write(line);
                writer.newLine();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        // Write
        writeCsv("output.csv",
            List.of("name", "age", "city"),
            List.of(
                List.of("Alice", "30", "New York"),
                List.of("Bob", "25", "Los Angeles")
            ));

        // Read
        var data = readCsv("output.csv");
        data.forEach(System.out::println);
    }
}

Use Cases

  • Parsing CSV data files without external libraries
  • Exporting data to CSV format
  • Data migration and import utilities

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.