Aniks Aniks - 1 year ago 106
Java Question

OpenCSV Avoid using FileWriter and return InputStream

I am using OpenCsv and the

new CSVWriter()
method takes a Writer as an argument.

What I am trying to achieve is that to avoid writing to the file system and instead return an
. I am not sure how to go about this. Not very familiar with
also I am using

Is it possible that I could make the writeValues method return an InputStream and avoid writing the output on file system.

This is my working implementation:

private static void writeValues(String[][] cellValues) throws IOException {

CSVWriter writer = new CSVWriter(new FileWriter("/tmp/myfile.csv"));
for(String[] row : cellValues) {

This is what I want to achieve.
How to Convert the above method to avoid using a FileWriter.

private static InputStream writeValues(String[][] cellValues) throws IOException {

InputStream inputStream = ?;

CSVWriter writer = new CSVWriter(?);
for(String[] row : cellValues) {

return inputStream;

Answer Source

Write to an OutpuStreamWriter itself writing to a ByteArrayOutputStream, and in the end, you'll have a byte array in memory (by calling getBytes() on the ByteArrayOutputStream).

You can then read from this byte array by opening a ByteArrayInputStream on the byte array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download