gpt4 book ai didi

java - 等待 Java 创建文件

转载 作者:行者123 更新时间:2023-11-30 05:41:14 24 4
gpt4 key购买 nike

我正在开发一个使用外部 C++ api 转换 pdf 的 Web API(使用 Spring Boot),该程序正在运行,但是当我想在正文响应中发送文件时,我收到此错误:

{
"timestamp": "2019-04-10T09:56:01.696+0000",
"status": 500,
"error": "Internal Server Error",
"message": "file [D:\\[Phenix-Monitor]1.pdf] cannot be resolved in the file system for checking its content length",
"path": "/convert/toLinPDf"}

Controller :

@PostMapping("/toLinPDf")
public ResponseEntity<ByteArrayResource> convertion(@RequestParam(value = "input", required = false) String in,
@RequestParam(value = "output", required = false) String out) throws IOException, InterruptedException {
linearizeService.LinearizePDf(in, out);
FileSystemResource pdfFile = new FileSystemResource(out);
return ResponseEntity
.ok()
.contentLength(pdfFile.contentLength())
.contentType(
MediaType.parseMediaType("application/pdf"))
.body(new ByteArrayResource(IOUtils.toByteArray(pdfFile.getInputStream())));

}

我猜问题出在 linearizeService.LinearizePDf(in, out); 因为在这个方法中我使用的是外部进程,所以发生的情况是当我尝试打开使用 FileSystemResource pdfFile = new FileSystemResource(out); 文件,线性化服务尚未完成处理,这就是为什么我收到此错误,我的问题是:我该如何处理这个问题,我的意思是如何等待文件创建然后发送该文件?

最佳答案

我建议您使用Java 8的Future API

这里是您的资源的更新。

@PostMapping("/toLinPDf")
public ResponseEntity<ByteArrayResource> convertion(
@RequestParam(value = "input", required = false) String in,
@RequestParam(value = "output", required = false) String out) throws IOException, InterruptedException {
ExecutorService executorService = Executors.newSingleThreadExecutor();
Callable<String> callable = () -> {
linearizeService.LinearizePDf(in, out);
return "Task ended";
};
Future<String> future = executorService.submit(callable);
String result = future.get();
executorService.shutdown();
FileSystemResource pdfFile = new FileSystemResource(out);
return ResponseEntity
.ok()
.contentLength(pdfFile.contentLength())
.contentType(
MediaType.parseMediaType("application/pdf"))
.body(new ByteArrayResource(IOUtils.toByteArray(pdfFile.getInputStream())));

}

关于java - 等待 Java 创建文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55610262/

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