【问题标题】:Running Command Line in Java using Runtime.getRuntime()使用 Runtime.getRuntime() 在 Java 中运行命令行
【发布时间】:2019-09-01 20:23:21
【问题描述】:

我正在使用 Spring Boot 创建 Web 应用程序,在此 Web 应用程序中我需要使用 Runtime.getRuntime() 运行命令行,但问题是:此命令在 Web 应用程序之后执行 这不是我想做的,问题是:

"如何确保 Runtime.getRuntime() 指令启动 当它在 Spring Boot 应用程序中被调用时(不是在它的末尾)"

控制器:

@PostMapping("/toLinPDf")
public ResponseEntity<ByteArrayResource> convertion(@RequestParam(value = "input", required = false) String in,
        @RequestParam(value = "output", required = false) String out) throws IOException, InterruptedException, ExecutionException {

    // the methode LinearizePDF contain the command line

    linearizeService.LinearizePDf(in, out);
    logger.warn("call the method linearizeService.LinearizePDf ");
    FileSystemResource result = new FileSystemResource(out);
    return ResponseEntity
            .ok()
            .contentLength(result.contentLength())
            .contentType(
                    MediaType.parseMediaType("application/pdf"))
            .body(new ByteArrayResource(IOUtils.toByteArray(result.getInputStream())));

}

linearizeService(包含方法 LinearizePDf(in, out)):

@Async
public void LinearizePDf(String Input , String Output) throws IOException, InterruptedException {
     Runtime rt = Runtime.getRuntime();

     // the command line 
     String command = "qpdf --linearize " + Input + "  " + Output;

     Process pr = rt.exec(command );
     logger.warn("run the command");
     pr.destroy();   
}

请,如果有任何建议,请不要犹豫。

谢谢!

【问题讨论】:

    标签: java spring-boot command-line process


    【解决方案1】:

    Quoting the well known site

    简单地说——用@Async注解一个bean的方法就可以了 在单独的线程中执行,即调用者不会等待 调用方法完成。

    LinearizePDf 中删除@Async

    此外,要等待外部进程完成,您应该使用waitFor 而不是destroy,例如pr.waitFor()

    【讨论】:

    • 其实我想做的是:“同时运行命令行和java程序”,在我的例子中,命令行在java应用程序完成运行时执行
    • 您是否删除了Async?它将使您有可能从控制器返回正确的ResponseEntity
    • 确实,我只是删除了@Async,我得到了相同的结果,它不工作。
    • 已添加waitFor - 查看答案
    • 好吧,我猜@Async 是问题的一部分,你是对的,所以我将其删除并将其放入控制器中,并且 FileSystemResource 也会以某种方式产生问题:" file [D:\[Phenix-Monitor ]1.pdf] 无法在文件系统中解析以检查其内容长度“所以我删除它并且它正在工作!
    猜你喜欢
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 2014-01-11
    相关资源
    最近更新 更多