Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To write different strings to a CSV file in Java while ensuring that commas are included, you can use a CSV writer library. One such library is the OpenCSV library, which you can add to your project by including the following dependency in your project's build.gradle file:

dependencies {
    implementation 'com.opencsv:opencsv:5.4'
}

Once you have added the OpenCSV library to your project, you can use the following code to write different strings to a CSV file:

import java.io.FileWriter;
import java.io.IOException;
import com.opencsv.CSVWriter;

public class CsvWriterExample {

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

      //create FileWriter object with file as parameter
      FileWriter outputfile = new FileWriter("output.csv");

      // create CSVWriter object with delimiter ',' and newline characters
      CSVWriter writer = new CSVWriter(outputfile, ',', 
              CSVWriter.DEFAULT_QUOTE_CHARACTER,
              CSVWriter.DEFAULT_ESCAPE_CHARACTER,
              CSVWriter.DEFAULT_LINE_END);

      // writing different strings to the CSV file
      String[] data1 = {"Name", "Age", "Gender"};
      writer.writeNext(data1);

      String[] data2 = {"John, Doe", "25", "Male"};
      writer.writeNext(data2);

      String[] data3 = {"Jane, Smith", "32", "Female"};
      writer.writeNext(data3);

      // closing writer connection
      writer.close();
   }
}

In this example, we first create a FileWriter instance using the output CSV file's name. Next, we create a CSVWriter instance using the FileWriter object, specifying the delimiter as a comma and the default newline character.

Finally, we write the different strings to the CSV file by creating string arrays with the data and calling the writeNext() method on the writer object. The writeNext() method will automatically encode the data as needed and include the commas in the output. Once we have written all the data, we close the writer to flush the output and release any resources.