如何从java程序在终端运行命令?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (57)

我需要通过JAVA程序在Fedora 16的终端上运行命令。我试过使用

Runtime.getRuntime().exec("xterm"); 

但是这只是打开终端,我无法执行任何命令。

我也试过这个:

OutputStream out = null;
Process proc = new ProcessBuilder("xterm").start();
out = proc.getOutputStream();  
out.write("any command".getBytes());  
out.flush(); 

但我仍然只能打开终端,但不能运行命令。有关如何去做的任何想法?

提问于
用户回答回答于

你不需要打开终端来运行命令。

例如,

// file: RunShellCommandFromJava.java
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class RunShellCommandFromJava {

    public static void main(String[] args) {

        String command = "ping -c 3 www.google.com";

        Process proc = Runtime.getRuntime().exec(command);

        // Read the output

        BufferedReader reader =  
              new BufferedReader(new InputStreamReader(proc.getInputStream()));

        String line = "";
        while((line = reader.readLine()) != null) {
            System.out.print(line + "\n");
        }

        proc.waitFor();   

    }
} 

输出:

$ javac RunShellCommandFromJava.java
$ java RunShellCommandFromJava
PING http://google.com (123.125.81.12): 56 data bytes
64 bytes from 123.125.81.12: icmp_seq=0 ttl=59 time=108.771 ms
64 bytes from 123.125.81.12: icmp_seq=1 ttl=59 time=119.601 ms
64 bytes from 123.125.81.12: icmp_seq=2 ttl=59 time=11.004 ms

--- http://google.com ping statistics ---
3 packets transmitted, 3 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 11.004/79.792/119.601/48.841 ms
用户回答回答于

你需要bash像这样使用可执行文件来运行它:

Runtime.getRuntime().exec("/bin/bash -c your_command");

更新: 正如xav所建议的,建议使用ProcessBuilder代替:

String[] args = new String[] {"/bin/bash", "-c", "your_command", "with", "args"};
Process proc = new ProcessBuilder(args).start();

扫码关注云+社区