[英]Run shell command from jar?
從Java調用shell命令的通常方法是這樣的:
Process process = Runtime.getRuntime().exec(command);
並且正常工作。 但是現在我已經將項目導出到可執行的jar文件中,並且callig shell命令不再起作用。 是否有此問題的解釋,解決方案或解決方法?
菲尼亞斯
-
編輯:
即使鍵盤中斷(ctrl + c; ctrl + d)也無法識別。
殺死Java后終端輸入不起作用
-
最小程序:
import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.IOException;
public class Test {
public static String fileName = "";
/** test if you can open a 7z archive file with a given password */
public static boolean test(String password)
throws IOException, InterruptedException {
String command = "7z l "+fileName;
Process process = Runtime.getRuntime().exec(command);
OutputStream out = process.getOutputStream();
OutputStreamWriter w = new OutputStreamWriter(out);
BufferedWriter writer = new BufferedWriter(w);
writer.write(password+"\n");
writer.close();
w.close();
out.close();
if(process.waitFor() == 0) {
return true;
}
else {
return false;
}
}
public static void main(String[] args) throws IOException, InterruptedException {
fileName = args[0];
test(args[1]);
}
}
如果運行測試程序並使用ps
或任務管理器,則會注意到7z
正在運行。 您的問題是您沒有使用流程的輸出。 因此7z
很快就被阻止嘗試輸出存檔內容。
如果您在process.waitFor()
之前添加以下行,則將獲得一個正常運行的程序:
InputStream in = process.getInputStream();
byte[] buf = new byte[256];
while (true) {
int c = in.read(buf);
if (c == -1)
break;
System.out.println(new String(buf));
}
但是,這只會消耗您需要使用process.getErrorStream()
進行相同處理的標准輸出。 您可能會發現使用ProcessBuilder
來啟動進程更容易,因為它允許您合並stderr和stdout流。
您應該閱讀這篇關於在Java中運行外部進程的陷阱的出色的JavaWorld文章 。
我猜您的問題出在執行命令的基本路徑上。 有一種方法可以在調用exec時顯式設置它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.