如何从java程序在终端运行命令? [英] how to run a command at terminal from java program?
本文介绍了如何从java程序在终端运行命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要通过 JAVA 程序在 Fedora 16 的终端上运行命令.我尝试使用
I need to run a command at terminal in Fedora 16 from a JAVA program. I tried using
Runtime.getRuntime().exec("xterm");
但这只是打开终端,我无法执行任何命令.
but this just opens the terminal, i am unable to execute any command.
我也试过这个:
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?
推荐答案
你需要像这样使用 bash
可执行文件来运行它:
You need to run it using bash
executable like this:
Runtime.getRuntime().exec("/bin/bash -c your_command");
更新:正如 xav 所建议的,建议使用ProcessBuilder 代替:
Update: As suggested by xav, it is advisable to use ProcessBuilder instead:
String[] args = new String[] {"/bin/bash", "-c", "your_command", "with", "args"};
Process proc = new ProcessBuilder(args).start();
这篇关于如何从java程序在终端运行命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文