OpenCSV避免使用FileWriter并返回InputStream

iih3973s  于 2022-12-06  发布在  其他
关注(0)|答案(4)|浏览(186)

我使用的是OpenCsv,new CSVWriter()方法将Writer作为参数。
我尝试实现的是避免写入文件系统,而是返回一个InputStream。我不知道如何去做。不太熟悉Streams,我也使用JAVA 7
我是否可以让writeValues方法返回一个InputStream,并避免将输出写入文件系统。
这是我的工作实现:

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

这就是我想要实现的。如何转换上述方法,以避免使用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;
}
dldeef67

dldeef671#

将Bean转换为字节数组的示例实现:

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

xv8emn3q2#

OutpuStreamWriter本身写ByteArrayOutputStream,最后,你会在内存中得到一个字节数组(通过在ByteArrayOutputStream上调用getBytes())。
然后,您可以开启字节数组上的ByteArrayInputStream,读取这个字节数组。

jv4diomz

jv4diomz3#

获取一个没有StatefulBeanToCsv的工作代码段,我不喜欢这样。

String[] headers = { "id", "result", "searchTerm"};
 ByteArrayOutputStream stream = new ByteArrayOutputStream();
 OutputStreamWriter streamWriter = new OutputStreamWriter(stream);
 CSVWriter writer = new CSVWriter(streamWriter);
 writer.writeNext(headers);
 // listOfRows -> business logic collection containing data for csv rows, as you can see I've separated the declaration of headers 
 listOfRows.forEach(it -> {
        writer.writeNext(new String[] {it.getId().toString(), it.getResult(), it.getSearchTerm()});
 });

 streamWriter.flush();
 byte[] byteArrayOutputStream = stream.toByteArray();
z9smfwbn

z9smfwbn4#

这是正确的实作

public static byte[] getBeansAsByteArray(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();
}

相关问题