2010-11-12 170 views
9

我創建了一個獨立的應用程序,我希望當用戶單擊運行按鈕時,終端應該打開並且應該在終端上執行特定的命令。我能打開終端成功地使用下面的代碼...在linux上通過java在終端上執行命令

Process process = null; 
try { 
    process = new ProcessBuilder("xterm").start(); 
} catch (IOException ex) { 
    System.err.println(ex); 
} 

上面的代碼打開一個終端窗口,但我不能在其上執行任何命令。誰能告訴我該怎麼做?

回答

2

假設你想你的gedit命令,那麼需要提供的gedit全限定路徑(例如在/ usr/bin中/ gedit中)。同樣,對於所有其他命令,請指定完整路徑。

5

嘗試

new ProcessBuilder("xterm", "-e", 
        "/full/path/to/your/program").start() 
+0

其實在終端我不想運行特定的程序。我需要執行一個特定的命令。例如,終端中的$ gedit。 – 2010-11-12 12:11:23

+0

是不是gedit程序? – Kennet 2010-11-12 12:17:57

+0

順便說一下,我爲了知識的緣故嘗試了上面給出的聲明,但它不起作用,甚至沒有終端打開。 – 2010-11-12 12:18:52

4

在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 [email protected] 'pg_dump -U postgres -w -h localhost db1 --schema-only'"; 
CommandExecutor.execute(command);