Execute external program from Java

Posted by Saurabh Lalwani on Stack Overflow See other posts from Stack Overflow or by Saurabh Lalwani
Published on 2010-05-20T14:22:36Z Indexed on 2010/05/20 14:30 UTC
Read the original article Hit count: 149

Filed under:
|
|

Hi, 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,

© Stack Overflow or respective owner

Related posts about java

Related posts about terminal