问题描述
我正在尝试从 Java 代码执行程序.这是我的代码:
I am trying to execute a program from the Java code. Here is my code:
public static void main(String argv[]) {
try {
String line;
Process p = Runtime.getRuntime().exec(
"/bin/bash -c ls > OutputFileNames.txt");
BufferedReader input = new BufferedReader(
new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
} catch (Exception err) {
err.printStackTrace();
}
}
我的操作系统是 Mac OS X 10.6.
My OS is Mac OS X 10.6.
如果我从 getRuntime().exec()
方法中删除 "> OutputFileNames.txt"
,所有文件名都打印在控制台上就好了.但我需要将它打印到文件中.
If I remove the "> OutputFileNames.txt"
from the getRuntime().exec()
method, all the file names are printed on the console just fine. But I need it to be printed to a file.
另外,如果我将命令更改为:
Also, if I change the command to:
Process p = Runtime.getRuntime().exec(
"cmd c dir > OutputFileNames.txt");
并在 Windows 上运行它,它运行并在文件中打印结果也非常好.
and run it on Windows, it runs and prints the results in the file perfectly fine too.
我已经阅读了其他关于从 Java 执行另一个应用程序的帖子,但似乎没有一个与我的问题有关.
I have read the other posts for executing another application from Java but none seemed to relate to my problem.
我真的很感激我能得到的任何帮助.
I would really appreciate any help I can get.
谢谢,
推荐答案
要使重定向按书面方式工作,您需要执行以下操作:
To get the redirection to work as written, you need to do this:
Process p = Runtime.getRuntime().exec(
new String[]{"/bin/bash", "-c", "ls > OutputFileNames.txt"});
您遇到的问题是 Runtime.exec(String)
将命令行拆分为参数的简单方法.
The problem you were running into is the simple-minded way that that Runtime.exec(String)
splits a command line into arguments.
如果您要在 shell 提示符下(按原样)运行该命令,则必须将其输入为:
If you were to run that command (as is) at a shell prompt, you would have had to have entered it as:
$ /bin/bash -c "ls > OutputFileNames.txt"
因为bash"的-c"选项需要将生成的 shell 的命令行作为单个 shell 参数.但是,如果您将裸引号放入 Java 字符串中,Runtime.exec(String)
方法仍然会出现拆分错误.唯一的解决方案是将命令参数作为数组提供.
because the "-c" option for "bash" requires the command line for the spawned shell as a single shell argument. But if you were to put the naked quotes into the Java String, the Runtime.exec(String)
method still get the splitting wrong. The only solution is to provide the command arguments as an array.
这篇关于从 Java 执行外部程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!