Ask Your Question
2

How can I write different strings to a CSV file in Java while also ensuring that commas are included?

asked 2021-07-21 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-08-09 14:00:00 +0000

david gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-07-21 11:00:00 +0000

Seen: 9 times

Last updated: Aug 09 '22