如何从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 :
String[] args = new String[] {"/bin/bash", "-c", "your_command", "with", "args"};
Process proc = new ProcessBuilder(args).start();
这篇关于如何从java程序在终端上运行命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文