[英]executing commands on terminal in linux through java
我創建了一個獨立的應用程序,我希望當用戶點擊運行按鈕時,終端應該打開,並且應該在終端上執行特定的命令。 我可以使用以下代碼成功打開終端...
Process process = null;
try {
process = new ProcessBuilder("xterm").start();
} catch (IOException ex) {
System.err.println(ex);
}
上面的代碼打開一個終端窗口,但我無法對其執行任何命令。 誰能告訴我怎么做?
嘗試
new ProcessBuilder("xterm", "-e",
"/full/path/to/your/program").start()
在linux中執行任何命令,就像你在終端中鍵入的那樣:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CommandExecutor {
public static String execute(String command){
StringBuilder sb = new StringBuilder();
String[] commands = new String[]{"/bin/sh","-c", command};
try {
Process proc = new ProcessBuilder(commands).start();
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(proc.getErrorStream()));
String s = null;
while ((s = stdInput.readLine()) != null) {
sb.append(s);
sb.append("\n");
}
while ((s = stdError.readLine()) != null) {
sb.append(s);
sb.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
用法:
CommandExecutor.execute("ps ax | grep postgres");
或者像以下一樣復雜:
CommandExecutor.execute("echo 'hello world' | openssl rsautl -encrypt -inkey public.pem -pubin | openssl enc -base64");
String command = "ssh user@database-dev 'pg_dump -U postgres -w -h localhost db1 --schema-only'";
CommandExecutor.execute(command);
假設您正在嘗試gedit命令,那么您需要提供gedit的完整限定路徑(例如/ usr / bin / gedit)。 同樣,對於所有其他命令,請指定完整路徑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.