Reputation: 165
I'm trying to use the opencsv library to write a csv file. The restriction being that I do not want to create a file on the disk or even a temp file. Is there a way I can achieve it?
From what I looked, the constructor for CSVWriter requires a FileWriter object.
Thanks!
Upvotes: 9
Views: 14565
Reputation: 724
To modify the example given here, just use a StringWriter instead of a FileWriter:
public static void main(String[] args) throws IOException {
String[] rowData = {"column1", "column2", "column3"};
try (StringWriter sw = new StringWriter(); CSVWriter csvWriter = new CSVWriter(sw)) {
csvWriter.writeNext(rowData);
String csv = sw.toString();
System.out.println("CSV result: \n" + csv);
}
}
Upvotes: 11
Reputation: 328556
Actually, CSVWriter
takes a Writer
instance, so you can simply pass a StringWriter
. After the write operation, you can ask the StringWriter
for it's content using toString()
.
Upvotes: 3
Reputation: 328598
Actually the constructor needs a Writer
and you could provide a StringWriter
to create a String.
Upvotes: 16