Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 InputStream. I am not sure how to go about this. Not very familiar with Streams also I am using JAVA 7.

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) { 
        writer.writeNext(row);
    }
    writer.close();
}

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) { 
        writer.writeNext(row);
    }
    writer.close();

    return inputStream;
}
like image 525
Aniks Avatar asked Mar 09 '16 06:03

Aniks


2 Answers

To supplement the answer JB Nizet gave:

public static byte[] getBeansAsByteArray(final List<YourBean> beans) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    OutputStreamWriter streamWriter = new OutputStreamWriter(stream);
    CSVWriter writer = new CSVWriter(streamWriter);

    StatefulBeanToCsv<YourBean> beanToCsv = new StatefulBeanToCsvBuilder(writer).build();
    beanToCsv.write(beans);
    streamWriter.flush();
    
    return stream.toByteArray();
}
like image 186
Michael Kemmerzell Avatar answered Sep 22 '22 02:09

Michael Kemmerzell


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.

like image 32
JB Nizet Avatar answered Sep 19 '22 02:09

JB Nizet