Working with CSV Files in Java: Read and Write Data with Ease
In this tutorial, you will learn how to read and write CSV (Comma-Separated Values) files in Java. CSV files are commonly used to store tabular data, and being able to handle them effectively is essential in many applications. By following this tutorial, you will gain a solid understanding of the process involved in reading data from a CSV file and writing data to it.
To effortlessly handle CSV data reading and writing operations, we will use the OpenCSV library. It is a Java library that provides a simple and efficient way to read and write CSV (Comma-Separated Values) files. It offers a straightforward API for parsing CSV data and converting it into Java objects, as well as for generating CSV data from Java objects.
Here are the steps to read and write a CSV file in Java using the OpenCSV library:
- Add the OpenCSV dependency to your project's build configuration file (e.g., Maven's pom.xml or Gradle's build.gradle). Include the following dependency:
- In your Java code, import the necessary classes from the OpenCSV library. Typically, you will need to import com.opencsv.CSVReader to read a CSV file and com.opencsv.CSVWriter to write to a CSV file. For example:
- To read a CSV file, create an instance of CSVReader by passing an instance of Reader and the desired delimiter character to its constructor. Then, you can use the readNext() method to read the file line by line, obtaining an array of values for each line. You can also use readAll() method to read the entire file into a List with each element being a String[] oftokens. Process the data as needed.
- To write data to a CSV file, create an instance of CSVWriter by passing an instance of Writer and the desired delimiter character to its constructor. Use the writeNext() method to write an array of values as a line in the CSV file. You can repeat this process for each line you want to write.
For Maven
<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>5.7.1</version> </dependency>
For Gradle
implementation group: 'com.opencsv', name: 'opencsv', version: '5.7.1'
import com.opencsv.CSVReader; import com.opencsv.CSVWriter;
Example 1: Reading the entire file into a List
try (CSVReader reader = new CSVReader(new FileReader("E:\\input.csv"))) { String[] row; int count = 0; while ((row = reader.readNext()) != null) { count++; System.out.println("Column 1 = " + row[0]); System.out.println("Column 2 = " + row[1]); System.out.println("Column 3 = " + row[2]); System.out.println("Column 4 = " + row[3]); System.out.println(" "); } System.out.println("Total number of rows = " + count); } catch (IOException | CsvValidationException e) { e.printStackTrace(); }
Example 2: Reading the file line by line
try (CSVReader reader = new CSVReader(new FileReader("E:\\input.csv"))) { Listlines = null; lines = reader.readAll(); for (String[] line : lines) { // Process each line of the CSV file for (String data : line) { System.out.print(data + " "); } System.out.println(); } } catch (IOException | CsvException e) { e.printStackTrace(); }
try (CSVWriter writer = new CSVWriter(new FileWriter("E:\\output.csv"))) { // creating a List of String array ListdataToWrite = new ArrayList (); dataToWrite.add(new String[] { "Name", "Email", "Year", "Programming" }); dataToWrite.add(new String[] { "John", "john@tb.com", "2021", "Java" }); dataToWrite.add(new String[] { "Danny", "danny@tb.com", "2020", "Python" }); dataToWrite.add(new String[] { "Lenny", "len@tb.com", "2021", "Go" }); dataToWrite.add(new String[] { "Sam", "sam@tb.com", "2019", "Node JS" }); writer.writeAll(dataToWrite); System.out.println("Complete"); } catch (IOException e) { e.printStackTrace(); }