java - 等待 Java 创建文件

标签 java file spring-boot

我正在开发一个使用外部 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/

相关文章:

java - 复杂 GUI 程序中的 MVC 模式

java - 数学错误开关总是以零结束

c - 从c中的文件中读取多行(不同长度)

spring-boot - 处理 Axon 事件时出现 ForbiddenClassException?

java - 为什么我们不重写 Spring CRUD Repository 中的方法

java - 删除一对一关系上的 jpa 实体

java - 在 AccessDeniedException 上检测到 Jackrabbit 未关闭的 session ,但 session 为空

java - 为什么在 catch InterruptException block 中调用 Thread.currentThread.interrupt()?

xml - Shell 脚本,如何使用 sed 替换 xml 文件中字符串的单个实例

C文件输入/梯形规则程序