javabeginner
CSV Parser — Read and Write CSV Files
Parse and write CSV files in Java without external libraries using BufferedReader and String operations.
javaPress ⌘/Ctrl + Shift + C to copy
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.
javabeginner
Read File Line by Line in Java
Read files using BufferedReader, Files.readAllLines, and Stream API with proper resource management.
Best for: Processing log files line by line
#java#file-io
javabeginner
ZIP Compression and Extraction
Compress and extract ZIP archives in Java using ZipOutputStream and ZipInputStream with directory support.
Best for: Creating ZIP archives for file downloads
#java#zip
javaintermediate
CLI Argument Parser
Parse command-line arguments with flags, options, positional args, and help text without external libraries.
Best for: Command-line tool argument parsing
#java#cli
typescriptintermediate
CSV Parse with Streaming
Parse large CSV files using Node.js streams with row-by-row processing and backpressure handling.
Best for: Data import pipelines
#csv#stream