有一种方法可以实现这一点,我们必须将数据作为 InputStream 发送
就我而言,我做了以下更改:
[1]我将我的 Bean 类更新为 Override toString() 方法,如下所示
public class Employee{
String Id;
String employeeNo;
String name;
//get and set
@Override
public String toString() {
return "{"+ Id +","+ employeeNo + ","+ name + "}";
}
[2]我取出数据列表,转换成List
List<Employee> employeeList=//get employee list
List<String[]> csvData = toStringArray(employeeList);
我的 toStringArray() 将返回 List
private List<String[]> toStringArray(List<Employee> employeeList) {
List<String[]> records = new ArrayList<String[]>();
// adding header to csv
records.add(new String[] { "EmployeeId", "EmployeeNo", "Name"});
// add data to csv
Iterator<Employee> emp = employeeList.iterator();
while (emp.hasNext()) {
Employee data = emp.next();
records.add(new String[] { emp.getId(), emp.getEmployeeNo(), emp.getName() });
}
return records;
}
[3] 现在我将此数据转换为字符串
String strCsvData=writeCsvAsString(csvData);
我的 writeCsvAsString() 方法是
public String writeCsvAsString(List<String[]> csvData) {
StringWriter s = new StringWriter();
CSVWriter writer = new CSVWriter(s);
writer.writeAll(csvData);
try {
writer.close();
} catch (IOException e) {
}
String finalString = s.toString();
logger.debug("Actual data:- {}", finalString);
return finalString;
}
现在我将此字符串转换为 InputStream 并将其发送到带有 contentType 元数据的 S3 存储桶 "text/csv"
InputStream targetStream = new ByteArrayInputStream(strCsvData.getBytes());