gpt4 book ai didi

java - 在 jersey rest api 中下载空 csv 文件

转载 作者:行者123 更新时间:2023-12-02 05:35:53 25 4
gpt4 key购买 nike

我正在尝试使用 REST API 下载 CSV 文件。我正在使用 opencsv 库将 Bean 转换为 csv。

我已经调试了所有输入,例如 inputData 和 fileName 都正常,并且 StatefulBeanToCsv正在写入输出流,但仍在下载空文件。请找到下面的代码

资源方法

@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
}

谁能帮我找出问题所在吗?提前致谢。

最佳答案

使用flush后,它会下载包含内容的文件。这是更改内容

@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 非常感谢您的评论

关于java - 在 jersey rest api 中下载空 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56165808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com