9

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!

LizardKing
  • 165
  • 1
  • 2
  • 8

3 Answers3

15

Actually the constructor needs a Writer and you could provide a StringWriter to create a String.

assylias
  • 321,522
  • 82
  • 660
  • 783
11

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);
    }
}
Leonid Dashko
  • 3,657
  • 1
  • 18
  • 26
mayhewsw
  • 704
  • 9
  • 20
3

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().

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820