2014-07-03 102 views
0

我正在嘗試從文件系統上的html文件讀取由phantomjs創建的pdf。我做了以下。Runtime.getRuntime().exec()未按預期方式工作

 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代碼調用時,它不能正常工作。如何解決這個問題?

+0

您可以發佈完整的命令,需要執行 – Sanjeev

+0

@Sanjeev phantomjs腳本? – phoenix

+0

由'phantomLocation + scriptLocation + inputFile +「」+ destinationFileString'創建的命令以及您在命令行上的執行方式 – Sanjeev

回答

0

看來問題在於你試圖用參數作爲單個字符串執行命令。你應該使用Runtime.exec(String[] comand)這樣的事情:

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

希望這會有所幫助。

+0

我正在獲取退出值-1的變化 – phoenix

+0

嘗試讀取進程的錯誤流/輸出流以獲得更多信息 – Sanjeev