【问题标题】:Runtime.getRuntime().exec() is not working as expectedRuntime.getRuntime().exec() 没有按预期工作
【发布时间】:2014-07-03 05:53:12
【问题描述】:

我正在尝试从文件系统上的 html 文件中读取由 phantomjs 创建的 pdf。我做了以下事情。

       process = Runtime.getRuntime().exec(phantomLocation + scriptLocation + inputFile + " " + destinationFileString);
       process.waitFor();

我正在指定 phantomLocation、js 脚本位置、inputHTML 和destinationFileString(要生成和提供的pdf)。

我正在编写以下 servlet 代码来读取生成的 pdf 并作为响应发送。

        InvokePhantom phantom = new InvokePhantom(inputHTMLFileName, destinationFile);
        process.create();//call the above piece of code
                //Set the response headers
                response.setContentType("application/pdf");
                String headerKey = "Content-Disposition";
                String headerValue = String.format("attachment; filename=\"%s\"", attchmentName);
                response.setHeader(headerKey, headerValue);

                //For debugging
                File file = new File(destinationFile);
                System.out.println("destinationFile exists = " + file.exists());

                //Write to outputStream
                fileInputStream = new FileInputStream(destinationFile);
                outputStream = response.getOutputStream();
                byte[] buffer = new byte[1024];
                int bytesRead = -1;
                while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

但是phantomjs生成的pdf文件不完整。从命令行运行时phantomjs 正在正确创建pdf(来自同一个html)。但是当从 java 代码调用时,它不能正常工作。如何解决问题?

【问题讨论】:

  • 能否请您发布需要执行的完整命令
  • @Sanjeev phantomjs 脚本?
  • phantomLocation + scriptLocation + inputFile + " " + destinationFileString 创建的命令以及您在命令行上的执行方式
  • @Sanjeev D:\Docs\phantomjs-1.9.7-windows\phantomjs.exe D:\Docs\screenshot.js C:\Users\AppData\Local\Temp\1404368319410330387378284269747.html C: \Users\AppData\Local\Temp\1404368319410.pdf 从命令行运行时,pdf 看起来很好,但不是来自 java 代码。
  • 尝试读取进程的错误流和输出流以查找可能的错误/输出

标签: java process runtime.exec


【解决方案1】:

似乎问题在于您正在尝试执行带有单个字符串的参数的命令。你应该使用Runtime.exec(String[] comand) 像这样:

String[] cmdArray = new String[]{phantomLocation,scriptLocation,inputFile,destinationFileString};
Process process = Runtime.getRuntime().exec(cmdArray);
process.waitFor();

希望这会有所帮助。

【讨论】:

  • 我得到了退出值 -1 的变化
  • 尝试阅读进程的错误流/输出流以获得更多洞察
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-19
  • 2020-03-18
  • 2012-06-14
  • 2014-11-15
相关资源
最近更新 更多