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

2022-09-01 06:27:54

我需要在 Fedora 16 中的终端从 JAVA 程序运行命令。我尝试使用

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

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

我也试过这个:

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

但我仍然只能打开终端,但无法运行命令。关于如何做到这一点的任何想法?


答案 1

您需要使用可执行文件运行它,如下所示: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();

答案 2

我投票支持Karthik T的答案。您无需打开终端即可运行命令。

例如

// 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

推荐