近日碰到了個需求,要整併外部的JAR到專案中,不過對方的JAR SIZE數十MB而自已所需要的只是裡面其中一個函式,故放入lib呼叫會造成專案封裝後的SIZE大增,不太OK~所以找到了ProcessBuilder這個好用的solution來,底下做個備忘囉!!
完工後的結果如下,效果如預期的方向呈現,OK的!
Process proc = null;
BufferedReader reader = null;
StringBuilder sbTravel = new StringBuilder();
try {
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("cmd", "/c", "java -jar d://hello.jar");
processBuilder.redirectErrorStream(true);
proc = processBuilder.start();
reader = new BufferedReader( new InputStreamReader(proc.getInputStream(), "Big5"));
String line;
while ((line = reader.readLine()) != null) {
if (StringUtils.isNotBlank(line)) sbTravel.append(line + "<br>");
}
int exitVal = proc.waitFor();
if (exitVal!=0) System.out.println("sbTravel:" + sbTravel + ",exitVal:" + exitVal);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) reader.close();
if (proc != null) proc.getOutputStream().close();
} catch (IOException e) {
System.out.println("has IOException:" + e.toString());
}
}
try {
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("cmd", "/c", "java -jar d://hello.jar");
processBuilder.redirectErrorStream(true);
proc = processBuilder.start();
reader = new BufferedReader( new InputStreamReader(proc.getInputStream(), "Big5"));
String line;
while ((line = reader.readLine()) != null) {
if (StringUtils.isNotBlank(line)) sbTravel.append(line + "<br>");
}
int exitVal = proc.waitFor();
if (exitVal!=0) System.out.println("sbTravel:" + sbTravel + ",exitVal:" + exitVal);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) reader.close();
if (proc != null) proc.getOutputStream().close();
} catch (IOException e) {
System.out.println("has IOException:" + e.toString());
}
}
補充:
間中也嘗試寫bat來執行,不過webSphere不給跑TOMCAT到是沒問題
Runtime.getRuntime().exec("cmd.exe /c start d:/hello.bat");
另外一個狀況是回傳值的取得,嘗試若干方法都沒能順利取值,間中也想過把console輸出寫成File來存取,但這方向容易有檔案被使用中卡住的exception(神奇的websphere),不然可以早些結案掉的。
Runtime.getRuntime().exec("java -jar d:/hello.jar > d:/bak/hello.TXT " );
後記:
2022-12-12 : 發行在WebSphere 9運行順利;但若改為WebSphere 8.5會拋送ssh handshake
exception,因此實作上等待伺服器更新緩不濟急因此用跳板方式轉到WebSphere 9的機器上
執行呼叫,缺點就是得多等個幾秒鐘。
沒有留言:
張貼留言