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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15356405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:26:23  来源:igfitidea点击:

how to run a command at terminal from java program?

javalinuxterminal

提问by phoenix

I need to run a command at terminal in Fedora 16 from a JAVA program. I tried using

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

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

but this just opens the terminal, i am unable to execute any command.

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

I also tried this:

我也试过这个:

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

but still i can only open the terminal, but can't run the command. Any ideas as to how to do it?

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

回答by SudoRahul

You need to run it using bashexecutable like this:

您需要使用这样的bash可执行文件运行它:

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

Update:As suggested by xav, it is advisable to use ProcessBuilderinstead:

更新:根据xav 的建议,建议改用ProcessBuilder

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

回答by Chris Cooper

You don't actually need to run a command from an xterm session, you can run it directly:

您实际上不需要从 xterm 会话运行命令,您可以直接运行它:

String[] arguments = new String[] {"/path/to/executable", "arg0", "arg1", "etc"};
Process proc = new ProcessBuilder(arguments).start();

If the process responds interactively to the input stream, and you want to inject values, then do what you did before:

如果进程以交互方式响应输入流,并且您想注入值,则执行您之前所做的操作:

OutputStream out = proc.getOutputStream();  
out.write("command\n");  
out.flush();

Don't forget the '\n' at the end though as most apps will use it to identify the end of a single command's input.

不要忘记末尾的“\n”,因为大多数应用程序将使用它来标识单个命令输入的结尾。

回答by user1252434

As others said, you may run your external program without xterm. However, if you want to run it in a terminal window, e.g. to let the user interact with it, xterm allows you to specify the program to run as parameter.

正如其他人所说,您可以在没有 xterm 的情况下运行您的外部程序。但是,如果您想在终端窗口中运行它,例如让用户与其交互,xterm 允许您指定要运行的程序作为参数。

xterm -e any command

In Java code this becomes:

在 Java 代码中,这变为:

String[] command = { "xterm", "-e", "my", "command", "with", "parameters" };
Runtime.getRuntime().exec(command);

Or, using ProcessBuilder:

或者,使用 ProcessBuilder:

String[] command = { "xterm", "-e", "my", "command", "with", "parameters" };
Process proc = new ProcessBuilder(command).start();

回答by shyan1

I vote for Karthik T's answer. you don't need to open a terminal to run commands.

我投票支持 Karthik T 的回答。您不需要打开终端来运行命令。

For example,

例如,

// 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();   

    }
} 

The output:

输出:

$ 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

回答by Akash Agarwal

I don't know why, but for some reason, the "/bin/bash" version didn't work for me. Instead, the simpler version worked, following the example given here at Oracle Docs.

我不知道为什么,但出于某种原因,“/bin/bash”版本对我不起作用。取而代之的是,按照Oracle Docs 中给出的示例,更简单的版本有效

String[] args = new String[] {"ping", "www.google.com"};
Process proc = new ProcessBuilder(args).start();

回答by mhashim6

I know this question is quite old, but here's a librarythat encapsulates the ProcessBuilder api.

我知道这个问题已经很老了,但这里有一个封装了 ProcessBuilder api的