Key Takeaways
- Reading CSV files in Java can be achieved using native classes like BufferedReader and Scanner.
- Storing CSV data into structures like ArrayLists makes it more manageable.
- Third-party libraries like Apache Commons CSV simplify advanced operations, like reading by column name.
CSV files are simple text files where each line represents a row of data, and fields within a row are separated by a delimiter, typically a comma.
Sample CSV File
First,Last,Age
John,Doe,23
Sam,Smith,40
Jan,Miller,18
The first line often acts as a header, outlining the column names:
First,Last,Age
Read a CSV File in Java - Using BufferedReader
import java.io.BufferedReader;
import java.io.FileReader;
public class CsvReader {
public static void main(String[] args) {
String file = "resources/data.txt";
String line;
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
Output
First,Last,Age John,Doe,23 Sam,Smith,40 Jan,Miller,18
The BufferedReader's readLine() method reads lines one-by-one. We use try-with-resources to ensure the buffer is closed safely.
Read CSV File into ArrayList
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CsvReader {
public static void main(String[] args) {
String file = "resources/data.txt";
String delimiter = ",";
String line;
List<List<String>> lines = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
while ((line = br.readLine()) != null) {
List<String> values = Arrays.asList(line.split(delimiter));
lines.add(values);
}
lines.forEach(System.out::println);
} catch (Exception e) {
System.out.println(e);
}
}
}
Output
[First, Last, Age] [John, Doe, 23] [Sam, Smith, 40] [Jan, Miller, 18]
Here we use split to convert each line into an array, storing each as an ArrayList entry.
Parse a CSV File Using Scanner
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class CsvReader {
public static void main(String[] args) {
String file = "resources/data.txt";
String delimiter = ",";
List<List<String>> lines = new ArrayList<>();
try (Scanner scanner = new Scanner(new File(file))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
List<String> values = Arrays.asList(line.split(delimiter));
lines.add(values);
}
lines.forEach(System.out::println);
} catch (Exception e) {
System.out.println(e);
}
}
}
Scanner provides a more flexible way to tokenize the input based on custom delimiters or line tokens.
Read a CSV File in Java with a Header
import java.io.BufferedReader;
import java.io.FileReader;
public class CsvReader {
public static void main(String[] args) {
String file = "resources/data.txt";
String headers;
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
headers = br.readLine();
System.out.println("Headers: " + headers);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
The header row is handled separately, allowing subsequent processing to ignore it.
Using Apache Commons CSV for Better Handling
For more advanced CSV processing, Apache Commons CSV is a robust choice. Add its dependency in your pom.xml:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>
</dependency>
Read a CSV File by Column Name
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import java.io.BufferedReader;
import java.io.FileReader;
public class CsvReader {
public static void main(String[] args) {
try (
BufferedReader br = new BufferedReader(new FileReader("resources/data.txt"));
CSVParser parser = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(br);
) {
for (CSVRecord record : parser) {
System.out.println(record.get("First"));
}
} catch (Exception e) {
System.out.println(e);
}
}
}
Output
John Sam Jan
Apache Commons CSV allows you to easily handle headers, delimiters, and other format specifics, making CSV parsing a breeze.
FAQ
Why use BufferedReader to read CSV files?
BufferedReader provides efficient processing of large data files due to its buffering capability, and it integrates seamlessly with Java's I/O framework.
What benefits does Apache Commons CSV offer?
Apache Commons CSV simplifies handling headers, delimiters, and record parsing, providing a more readable and maintainable approach for CSV operations.
When should I use Scanner instead of BufferedReader?
Scanner is suitable for reading complex data inputs where you need to tokenize the input based on varied delimiters, though it's slightly less efficient for simple line-by-line processing compared to BufferedReader.
Can I handle CSV encoding issues with these tools?
Java I/O classes like BufferedReader and libraries like Apache Commons CSV can handle encoding by properly setting character encodings where needed, such as UTF-8.
