从Java执行外部程序 [英] Execute external program from Java

查看:89
本文介绍了从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();
    }
}

我的操作系统是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非常感谢我能得到的任何帮助。

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

您遇到的问题是那种运行时的简单方法.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执行外部程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆