Execute external program from Java

后端 未结 3 1669
感情败类
感情败类 2020-12-03 22:30

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 =         


        
3条回答
  •  独厮守ぢ
    2020-12-03 23:19

    The problem is happening because standard output of the process is being directed to the file, so the java Process cannot collect the output.

    If you want the output written to a file, and be available for reading in java, then you have two options:

    1. Keep the redirect in place, and then read the listing from the OutputFile.txt in java, e.g. using new FileReader("OutputFile.txt"). Note that exec() is asynchronous, and can return before the process has finished writing to file, so you will need to wait for the Process to exit, by using Process.waitFor().
    2. Remove the redirect, and read the listing directly into java (as you are doing.) You can then write this listing out to a file using FileWriter.

    The bottom line is that you can't use both redirect and read the output from the Process at the same time - it's one or the other.

    EDIT: Your comments indicate that 1) is the preferred approach. This will write the output to a file (using the OS shell) which you then read in from java when the process exits.

提交回复
热议问题