OpenCSV 避免使用 FileWriter 和 return InputStream

OpenCSV Avoid using FileWriter and return InputStream

我正在使用 OpenCsv,new CSVWriter() 方法将 Writer 作为参数。

我想要实现的是避免写入文件系统,而是 return InputStream。我不知道该怎么做。不太熟悉 Streams 我也在使用 JAVA 7.

是否可以使 writeValues 方法 return 成为 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;
}

写入 OutpuStreamWriter 本身写入 ByteArrayOutputStream,最后,您将在内存中拥有一个字节数组(通过调用 getBytes() [=11] =]).

然后您可以通过在字节数组上打开 ByteArrayInputStream 来读取此字节数组。

补充 JB Nizet 给出的答案:

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

这是正确的实现

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

获取一个我不喜欢的没有 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();