CSV file parsing using Open CSV library

A CSV file is a comma-separated values file used for importing and exporting the data from the application. The CSV file consists of one or more columns separated with a delimiter comma. In this tutorial, we are going to see how to parse the CSV file using the Native Java program and using the Open CSV library.

Using Native Java Program:

 

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class CsvFileTest {
    public static void main(String[] args) {
        CsvFileTest csvFile = new CsvFileTest();
        csvFile.readCsvFile(); // read csv file
        csvFile.createNewCsvFile();//create new file
    }
    public void readCsvFile() {
        
        //Path of the file name , if it is not given it will take the root for the workspace.
        String filePath = "ReadCsv.csv";
        try {
            Scanner scanner = new Scanner(new File(filePath));
            scanner.useDelimiter(",");//split by ","
            while (scanner.hasNext()) {
                String data = scanner.next();
                System.out.print(data + " ");
            }
            scanner.close();
        } catch (Throwable ignored) {
        }
    }
    public void createNewCsvFile() {
        //Path of the file name , if it is not given it will take the root for the workspace.
        String filePath = "newCsvFile.csv";
        List> rows = Arrays.asList(
                Arrays.asList("Windows", "Windows10", "2020"), //add data as corresponding header format
                Arrays.asList("Ubuntu", "Mantic Minotaur", "2023"),
                Arrays.asList("MAC", "Sonoma", "2022")
        );
        try {
            //add headers
            FileWriter writer = new FileWriter(filePath);
            writer.append("OS");
            writer.append(",");
            writer.append("VersionName");
            writer.append(",");
            writer.append("YearOfMake");
            writer.append("\n");
            //write csv file
            for (List rowData : rows) {
                writer.append(String.join(",", rowData));
                writer.append("\n");
            }
            //save
            writer.flush();
            writer.close();
        } catch (Throwable e) {
            System.out.println("error " + e);
        }
    }
}

 

Using Open CSV Library :

The OpenCsv is an Open source Java library to parse CSV files effectively. We can read, and write the CSV file easily through the predefined methods given 
in the OpenCsv library.

Below Maven dependency needs to be given in pom.xml

 

<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>5.7.1</version>
</dependency>


Read CSV file line by line :

 

import com.opencsv.CSVParser;
import com.opencsv.CSVParserBuilder;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.exceptions.CsvValidationException;
import java.io.*;
import java.net.URL;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class OpenCsvFileTest {
    public static void main(String[] args) throws IOException, CsvValidationException {
        String[] lineValue;
        CSVParser builder = new CSVParserBuilder()
                .withSeparator(',')
                .withIgnoreQuotations(true)
                .build();
        CSVReader reader = new CSVReaderBuilder(new FileReader("ReadCsv.csv"))
                .withSkipLines(1) // to skip the first line if the Header is given
                .withCSVParser(builder)
                .build();
        
        // Print line by line 
        while ((lineValue = reader.readNext()) != null) {
              System.out.println(Arrays.toString(lineValue));
        }
    }
}

 

Read CSV file using Java Object

Steps:

Create the class with the same Header given in the CSV file, for example OS, VersionName, YearOfMake and annotate with @CsvBindByPosition. We can also use @CsvBindByName annotation to specify the CSV columns and the member fields.

import com.opencsv.bean.CsvBindByPosition;
public class OperatingSysName {
    @CsvBindByPosition(position = 0)
    private String OS;
    @CsvBindByPosition(position = 1)
    private String VersionName;
    public String getOS() {
        return OS;
    }
    public String getVersionName() {
        return VersionName;
    }
    public String getYearOfMake() {
        return YearOfMake;
    }
    @CsvBindByPosition(position = 2)
    private String YearOfMake;
}
 
Use the CsvToBean class to map the Class File OperatingSysName
 
package org.example;
import com.opencsv.CSVParser;
import com.opencsv.CSVParserBuilder;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.exceptions.CsvValidationException;
import java.io.*;
import java.util.Iterator;
public class OpenCsvFileTest {
    public static void main(String[] args) throws IOException, CsvValidationException {
        
        // Read the CSV file 
        Reader reader = new BufferedReader(new FileReader("filepath.csv"));
        CsvToBean csvRead = new CsvToBeanBuilder(reader)
                .withSkipLines(1)
                .withType(OperatingSysName.class)
                .withSeparator(',')
                .withIgnoreLeadingWhiteSpace(true)
                .withIgnoreEmptyLine(true)
                .build();
        
        Iterator results = csvRead.iterator();
        while(results.hasNext()){
            OperatingSysName ss = results.next();
            System.out.println(ss.getOS());
            System.out.println(ss.getVersionName());
            System.out.println(ss.getYearOfMake());
        }
    }
}

 

Write CSV file:

We can write the data into the CSV file using CSVWriter class

 

import com.opencsv.CSVWriter;
import java.io.FileWriter;
public class OpenCsvWriteFile {

    public static void main(String[] args) throws Exception {

        CSVWriter writer = new CSVWriter(new FileWriter("OsDetails.csv"));
        String[] osData = "OS,VersionName,YearOfMake".split(",");
        
        //Write the data in to file
        writer.writeNext(osData, false);
        //close the writer
        writer.close();
    }
}

 

Related Tutorials

Related Questions






Read more