首先terminl
,您可以简单地运行以下代码:
new ProcessBuilder("/usr/bin/xterm").start();
但我想,那不是你真正需要的。因为,即使你传递命令来运行,让我们说ls
作为参数:
new ProcessBuilder("/usr/bin/xterm", "-e", "ls").start();
您将从xterm
(而不是ls
)获得输出。如果你想启动进程并获得输出,你需要这样做:
public static void main(String[] args) throws Exception {
// get content of the "/usr/bin" directory
ProcessBuilder pb = new ProcessBuilder("ls", "/usr/bin");
pb.redirectErrorStream(true);
Process p = pb.start();
InputStream is = p.getInputStream();
System.out.println(toString(is));
is.close();
}
public static String toString(InputStream is) throws IOException {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
return writer.toString();
}