java 外部程序,从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();

}

}

My OS is Mac OS X 10.6.

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");

and run it on Windows, it runs and prints the results in the file perfectly fine too.

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.

Thanks,

解决方案

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"});

The problem you were running into is the simple-minded way that that Runtime.exec(String) splits a command line into arguments.

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"

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值