等到在 Java 中创建文件

我正在开发一个Web API(使用弹簧启动),使用外部C++api转换pdf,该程序正在工作,但是当我想在正文响应中发送文件时,我收到此错误:


{

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

控制器:


@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尚未完成处理,为什么我得到这个错误,我的问题是:我该如何处理这个问题,我的意思是如何等待文件被创建然后发送这个文件?linearizeService.LinearizePDf(in, out);FileSystemResource pdfFile = new FileSystemResource(out);


海绵宝宝撒
浏览 238回答 1
1回答

幕布斯6054654

我建议你使用Java 8。Future API这是您的资源的更新。@PostMapping("/toLinPDf")public ResponseEntity<ByteArrayResource> convertion(&nbsp; &nbsp; @RequestParam(value = "input", required = false) String in,&nbsp; &nbsp; @RequestParam(value = "output", required = false) String out) throws IOException, InterruptedException {ExecutorService executorService = Executors.newSingleThreadExecutor();Callable<String> callable = () -> {&nbsp; &nbsp; &nbsp; &nbsp; linearizeService.LinearizePDf(in, out);&nbsp; &nbsp; &nbsp; &nbsp; return "Task ended";};Future<String> future = executorService.submit(callable);String result = future.get();executorService.shutdown();FileSystemResource pdfFile = new FileSystemResource(out);return ResponseEntity&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .ok()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .contentLength(pdfFile.contentLength())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .contentType(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; MediaType.parseMediaType("application/pdf"))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .body(new ByteArrayResource(IOUtils.toByteArray(pdfFile.getInputStream())));}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java