我使用的函数将输入List和className,我将List转换为分隔符文件(Intermediate),然后将文件转换为InputStream作为返回值。
在这里创建一个中间文件并删除是一个繁琐的过程,因为这会增加时间和性能。
还有另一种方法可以直接将数据从List<Class>
转换为带有标题的分隔符(也许我们可以将它存储在List<Object>
中)然后不创建中间文件我们可以直接将其转换为InputStream。
<T> InputStream createInputStream(String csvFileName, List<T> listObject, Class className, char csvPreference) {
ICsvBeanWriter beanWriter = null;
File file=new File(csvFileName);
InputStream inputStream=null;
try {
CsvPreference DELIMITER = new CsvPreference.Builder('"', csvPreference, "\n").build();
beanWriter = new CsvBeanWriter(new FileWriter(file), DELIMITER);
List<String> fieldList = Arrays.stream(className.getDeclaredFields()).map(Field::getName).collect(Collectors.toList());
CellProcessor[] processors = new CellProcessor[fieldList.size()];
for (int i = 0; i < fieldList.size(); i++) {
processors[i] = new Optional();
}
String[] header = new String[fieldList.size()];
fieldList.toArray(header);
beanWriter.writeHeader(header);
for (T obj : listObject) {
beanWriter.write(obj, header, processors);
}
} catch (IOException ex) {
System.err.println("Error writing the CSV file: " + ex);
} finally {
if (beanWriter != null) {
try {
beanWriter.close();
inputStream=new FileInputStream(file);
file.delete();
} catch (IOException ex) {
System.err.println("Error closing the writer: " + ex);
}
}
}
return inputStream;
}
用户类
public class Users {
String id;
String name;
String gender;
}
在列表中添加元素
List<Users> userList=new ArrayList<Users>();
userList.add(new Users("1","AA","Male"));
userList.add(new Users("2","BB","Male"));
userList.add(new Users("3","CC","Female"));
此处我正在调用
InputStream inputStream=createInputStream("demo.csv",userList,Users.Class,'|');
这里的中级文件(demo.csv)就像,
id|name|gender
1|AA|Male
2|BB|Male
3|CC|Female
从这个文件中,我将转换为输入流
先谢谢你,周杰伦
答案 0 :(得分:3)
您是否考虑过像
这样的内容ByteArrayOutputStream baos = new ByteArrayOutputStream();
beanWriter = new CsvBeanWriter(new PrintWriter(baos), DELIMITER);
//write some stuff
byte[] byteArray = baos.toByteArray();
return new ByteArrayInputStream(byteArray);