通过java在linux上的终端上执行命令

时间:2010-11-12 12:02:14

标签: java linux command terminal processbuilder

我创建了一个独立的应用程序,我希望当用户点击运行按钮时,终端应该打开,并且应该在终端上执行特定的命令。我可以使用以下代码成功打开终端...

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

上面的代码打开了一个终端窗口,但我无法对其执行任何命令。谁能告诉我怎么做?

3 个答案:

答案 0 :(得分:5)

尝试

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

答案 1 :(得分: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 user@database-dev 'pg_dump -U postgres -w -h localhost db1 --schema-only'";
CommandExecutor.execute(command);

答案 2 :(得分:2)

假设您正在尝试gedit命令,那么您需要提供gedit的完整限定路径(例如/ usr / bin / gedit)。同样,对于所有其他命令,请指定完整路径。