[英]Runtime.getRuntime().exec() is not working as expected
我正在嘗試從文件系統上的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代碼調用時,它無法正常工作。 該如何解決呢?
看來問題是您正在嘗試將參數作為單個String執行命令。 您應該使用Runtime.exec(String [] comand)這樣的東西:
String[] cmdArray = new String[]{phantomLocation,scriptLocation,inputFile,destinationFileString};
Process process = Runtime.getRuntime().exec(cmdArray);
process.waitFor();
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.