我正在尝试使用rest api下载CSV文件。我正在使用opencsv库将Bean转换为csv。
我已经调试完所有输入,例如inputData和fileName都正确,并且StatefulBeanToCsv正在写入outputstream,但仍在下载空文件。请在下面找到代码
资源方法
@GET
@Path("/{category}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadAdminFile(@PathParam("category") String adminFileCategory,@QueryParam ("subCategory") String subCategory) {
AdminFileStreamingOutput streamingOutput = adminFileDataService.downloadAdminFile(adminFileCategory,subCategory);
return Response.ok(streamingOutput).header("Content-Disposition", "attachment; filename=" + streamingOutput.getFileName() + ";" + "charset=UTF-8")
.build();
}
AdminFileStreamingOutput.java
public class AdminFileStreamingOutput implements StreamingOutput {
private Collection<?extends Serializable> inputData;
private String fileName;
public AdminFileStreamingOutput(Collection<?extends Serializable> inputData,String fileName) {
this.inputData = inputData;
this.fileName = fileName;
}
@Override
public void write(OutputStream output) throws IOException, WebApplicationException {
StatefulBeanToCsvBuilder builder = new StatefulBeanToCsvBuilder(new OutputStreamWriter(output));
StatefulBeanToCsv beanWriter = builder
.withSeparator(';')
.build();
try {
beanWriter.write(this.inputData.iterator());
} catch (CsvDataTypeMismatchException | CsvRequiredFieldEmptyException e) {
throw new RuntimeException("Failed to download admin file");
}
}
public String getFileName() {
return fileName;
}
}
使用OpenCSV注释进行映射策略的Bean之一
public class ProjectInfo implements Serializable {
@CsvBindByName(column = "ProjectName",required = true)
private String projectName;
@CsvBindByName(column = "ProjectCode",required = true)
private String projectCode;
//setters and getters
}
有人可以帮我找出问题吗?预先感谢。
答案 0 :(得分:0)
使用冲洗后,它将下载包含内容的文件。这是更改
@Override
public void write(OutputStream output) throws IOException, WebApplicationException {
try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output))){
StatefulBeanToCsvBuilder builder = new StatefulBeanToCsvBuilder(writer);
StatefulBeanToCsv beanWriter = builder
.withSeparator(';').build();
try {
beanWriter.write(this.inputData.iterator());
writer.flush();
} catch (CsvDataTypeMismatchException | CsvRequiredFieldEmptyException e) {
throw new CMMV1Exception("Failed to download admin file");
}
}
}
@ Paul Samsotha非常感谢您的评论