Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

macos - Execute external program from 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(new String[]{
          "/bin/bash", "-c", "executable -o filename.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.

Now, the executable I am trying to run is supposed to spit the output to filename.txt. If I take this command and run it on the terminal, it works fine and the filename.txt gets populated also. But, from my java program the file is not created.

if instead I use executable > filename.txt then the filename.txt is created but is empty. Not sure what's wrong here. The executable I am trying to run is Xtide (if that helps).

I would really appreciate any help I can get.

Thanks,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You cannot redirect output to file and read the output in java. It's one or the other. What you want is this:

      Process p = Runtime.getRuntime().exec(new String[]{
          "/bin/bash", "-c", "executable -o filename.txt"});
      p.waitFor();
      BufferedReader input = new BufferedReader(
          new InputStreamReader(new FileInputStream("filename.txt")));
      while ((line = input.readLine()) != null) {
        System.out.println(line);
      }

The main changes are:

  • p.waitFor(), since process execution is asynchronous, so you have to wait for it to complete.
  • The data is read from the file rather than from the output of the process (since this will be empty.)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...