在linux上通过java在终端上执行命令
问题描述:
我创建了一个独立的应用程序,我希望当用户单击运行按钮时,终端应该打开并且应该在终端上执行特定的命令。我能打开终端成功地使用下面的代码...在linux上通过java在终端上执行命令
Process process = null;
try {
process = new ProcessBuilder("xterm").start();
} catch (IOException ex) {
System.err.println(ex);
}
上面的代码打开一个终端窗口,但我不能在其上执行任何命令。谁能告诉我该怎么做?
答
假设你想你的gedit命令,那么需要提供的gedit全限定路径(例如在/ usr/bin中/ gedit中)。同样,对于所有其他命令,请指定完整路径。
答
尝试
new ProcessBuilder("xterm", "-e",
"/full/path/to/your/program").start()
答
在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);
其实在终端我不想运行特定的程序。我需要执行一个特定的命令。例如,终端中的$ gedit。 – 2010-11-12 12:11:23
是不是gedit程序? – Kennet 2010-11-12 12:17:57
顺便说一下,我为了知识的缘故尝试了上面给出的声明,但它不起作用,甚至没有终端打开。 – 2010-11-12 12:18:52