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!

3 Answers 3

16

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

Sign up to request clarification or add additional context in comments.

Comments

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);
    }
}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.