• Create CSV File in Java

    How to create CSV File in Java

    This example will show you how you can create csv file in java using OpenCSV dependency.
    If you’re using maven, add the opencsv dependency in your pom.xml

    
        <groupId>com.opencsv</groupId>
        <artifactId>opencsv</artifactId>
        3.7
    
    

    or download the jar file in maven central or here

    Next, use CSVWriter class to create your csv file:

    import com.opencsv.CSVWriter;
    
    import java.io.FileWriter;
    import java.io.IOException;
    
    public class CSVExample {
    
        public static void main(String[] args) throws IOException {
            CSVWriter csvWriter = new CSVWriter(new FileWriter("example.csv"));
            csvWriter.writeNext(new String[]{"1", "jan", "Male", "20"});
            csvWriter.writeNext(new String[]{"2", "con", "Male", "24"});
            csvWriter.writeNext(new String[]{"3", "jane", "Female", "18"});
            csvWriter.writeNext(new String[]{"4", "ryo", "Male", "28"});
    
            csvWriter.close();
        }
    }
    


    This will create a file with name example.csv in your project root path. If opened in notepad, this will result to the following contents:

    "1","jan","Male","20"
    "2","con","Male","24"
    "3","jane","Female","18"
    "4","ryo","Male","28"
    

    If your data is in List<String[]> collection object, you can just use the method CSVWriter#writeAll method. Here is an example of passing List object to CSVWriter:

    import com.opencsv.CSVWriter;
    
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.LinkedList;
    import java.util.List;
    
    public class CSVExample {
    
        public static void main(String[] args) throws IOException {
            CSVWriter csvWriter = new CSVWriter(new FileWriter("example.csv"));
    
            List<String[]> rows = new LinkedList<String[]>();
            rows.add(new String[]{"1", "jan", "Male", "20"});
            rows.add(new String[]{"2", "con", "Male", "24"});
            rows.add(new String[]{"3", "jane", "Female", "18"});
            rows.add(new String[]{"4", "ryo", "Male", "28"});
            csvWriter.writeAll(rows);
    
            csvWriter.close();
        }
    }
    

    Take note that we have used LinkedList as the implementation of the list to preserved the insertion order. The above code when run will result to the same output. Also, by default, the csv values are enclosed by double quotations(“”). If you don’t want to add quotes, you can add a second argument false to the CSVWriter methods which will skip applying quotes to all values.

    Related Post