我正在使用OpenCsv,new CSVWriter()
方法将Writer作为参数。
我试图实现的是避免写入文件系统,而是返回InputStream
。我不知道该怎么做。不太熟悉Streams
我也在使用JAVA 7
.
我是否有可能使 writeValues 方法返回输入流并避免在文件系统上写入输出。
这是我的工作实现:
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();
}
这就是我想要实现的目标。如何转换上述方法以避免使用文件编写器。
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;
}
将 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();
}
写入OutpuStreamWriter
本身写入ByteArrayOutputStream
,最后,您将在内存中拥有一个字节数组(通过在ByteArrayOutputStream
上调用getBytes()
)。
然后,您可以通过在字节数组上打开一个ByteArrayInputStream
来读取此字节数组。
获取一个没有 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();
这是正确的实现
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();
}