Writing CSV to String using opencsv without creating the actual file or temporary file

I am trying to use the opencsv library to write a csv file. The limitation is that I do not want to create a file on disk or even a temporary file. Is there any way I can achieve this?

From what I looked, the constructor for CSVWriter requires a FileWriter object.

Thanks!

+6
source share
3 answers

In fact, the constructor needs a Writer , and you can provide a StringWriter to create a string.

+8
source

To modify the example below, simply use StringWriter instead of FileWriter:

 public static void main(String[] args) throws IOException { StringWriter s = new StringWriter(); CSVWriter writer = new CSVWriter(s, '\t'); // feed in your array (or convert your data to an array) String[] entries = "first#second#third".split("#"); writer.writeNext(entries); writer.close(); String finalString = s.toString(); System.out.println(finalString); } 
+6
source

Actually, CSVWriter accepts an instance of Writer , so you can just pass a StringWriter . After the write operation, you can query StringWriter for this content with toString() .

+2
source

All Articles