本文介绍了Java - 使用选项执行程序,如 ls -l的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Java 中,如何执行带有选项的 linux 程序,如下所示:
In Java, how do I execute a linux program with options, like this:
ls -a
(选项是-a),
和另一个:./myscript name=john age=24
我知道如何执行命令,但不能执行选项.
I know how to execute a command, but cannot do the option.
推荐答案
You need to execute an external process, take a look at ProcessBuilder and just because it almost answers your question, Using ProcessBuilder to Make System Calls
更新示例
我直接从列表示例中提取并修改了它,以便我可以在我的 PC 上进行测试并且它运行良好
I ripped this straight from the list example and modified it so I could test on my PC and it runs fine
private static void copy(InputStream in, OutputStream out) throws IOException {
while (true) {
int c = in.read();
if (c == -1) {
break;
}
out.write((char) c);
}
}
public static void main(String[] args) throws IOException, InterruptedException {
// if (args.length == 0) {
// System.out.println("You must supply at least one argument.");
// return;
// }
args = new String[] {"cmd", "/c", "dir", "C:\"};
ProcessBuilder processBuilder = new ProcessBuilder(args);
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
copy(process.getInputStream(), System.out);
process.waitFor();
System.out.println("Exit Status : " + process.exitValue());
}
这篇关于Java - 使用选项执行程序,如 ls -l的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!