Java: How to write data in CSV file using OpenCSV library

By: Slav Kurochkin

In my current project I'm storing value in a property file, then getting it and parsing to the CSV file, which later on I will need to upload to the software. There is enough CSV parser libraries out there, I use OpenCSV, the reason why, well, it is simple and solving my problem. Here is how you do it:

 public static void writeCSV() {

// getting value from property file
      String c_code = getDataValue("cCode");

      System.out.println("Here is what we got: " + c_code);

        try {

            String currentDir = System.getProperty("user.dir");
             System.out.println(currentDir);
            BufferedWriter out = new BufferedWriter(new FileWriter(currentDir + "/cCodeTest.csv"));
            CSVWriter writer = new CSVWriter(out);
            String[] values = {"1", "110808", "26", "0", "123456789", "90", c_code, "First Lastname", "C01", "CorrectionInfo",c_code};
            writer.writeNext(values);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

I use maven dependency in order to get library to my project:

 <dependency>
            <groupId>com.opencsv</groupId>
            <artifactId>opencsv</artifactId>
            <version>3.3</version>
        </dependency>
View Comments

Leave a Comment

Use markdown or basic HTML and be nice.