Reading data from a CSV file is a common task in Java programming. In this post, we’ll learn how to read a CSV file, parse its contents, and store the data into an ArrayList of objects.
✅ CSV Example
Let’s assume you have a file called employees.csv with the following content:
id,name,department
1,John Doe,Engineering
2,Jane Smith,Marketing
3,Robert Brown,Finance
📦 Step 1: Create a Java Class
We’ll start by defining an Employee class to represent each row of the CSV file.
public class Employee {
private int id;
private String name;
private String department;
public Employee(int id, String name, String department) {
this.id = id;
this.name = name;
this.department = department;
}
@Override
public String toString() {
return id + ", " + name + ", " + department;
}
}
🧑💻 Step 2: Read the CSV and Convert to ArrayList
Here’s a complete example using BufferedReader:
import java.io.*;
import java.util.*;
public class CSVReaderExample {
public static void main(String[] args) {
String filePath = "employees.csv";
List<Employee> employees = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
boolean header = true;
while ((line = br.readLine()) != null) {
if (header) {
header = false; // skip header line
continue;
}
String[] parts = line.split(",");
int id = Integer.parseInt(parts[0]);
String name = parts[1];
String department = parts[2];
employees.add(new Employee(id, name, department));
}
} catch (IOException e) {
e.printStackTrace();
}
// Print all employees
for (Employee emp : employees) {
System.out.println(emp);
}
}
}
📊 Output
The output will look like:
1, John Doe, Engineering
2, Jane Smith, Marketing
3, Robert Brown, Finance
📝 Notes:
- The CSV file must be placed in your project root directory or use the full path.
- You can use String.split() for simple CSVs, but for more complex files with quoted fields or commas in values, consider using libraries like OpenCSV.
📦 Bonus: Add Table Format for Display (Optional)
If you want a cleaner display:
System.out.printf("%-5s %-20s %-15s\n", "ID", "Name", "Department");
for (Employee emp : employees) {
System.out.printf("%-5d %-20s %-15s\n", emp.id, emp.name, emp.department);
}
Output Table:
ID Name Department
1 John Doe Engineering
2 Jane Smith Marketing
3 Robert Brown Finance
This approach is great for learning file handling and object-oriented parsing in Java. Let me know if you want the same using OpenCSV or other libraries!
Leave a Reply