Capture the output of an external program in JAVA

前端 未结 2 1795
说谎
说谎 2021-01-12 04:00

I\'m trying to capture output of an external program using java but I can\'t.

I have the code to show it, but not to put it into a variable.

I will use, for

相关标签:
2条回答
  • 2021-01-12 04:19

    Use Apache Commons Exec, it will make your life much easier. Check the tutorials for information about basic usage. To read the command line output after obtaining an executor object (probably DefaultExecutor), create an OutputStream to whatever stream you wish (i.e a FileOutputStream instance may be, or System.out), and:

    executor.setStreamHandler(new PumpStreamHandler(yourOutputStream));
    
    0 讨论(0)
  • 2021-01-12 04:26

    Because the Process will execute in a new thread it's likely that there is no output or incomplete output available when you come to your while loop.

    Process p = pb.start();  
    // process runs in another thread parallel to this one
    
    BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream()));
    
    // bri may be empty or incomplete.
    while ((line = bri.readLine()) != null) {
        RESULT+=line;
    }
    

    So you need to wait for the process to complete before attempting to interact with it's output. Try using the Process.waitFor() method to pause the current thread until your process has had an opportunity to complete.

    Process p = pb.start();  
    p.waitFor();  // wait for process to finish then continue.
    
    BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream()));
    
    while ((line = bri.readLine()) != null) {
        RESULT+=line;
    }
    

    This is only a simple approach you could also process the output of the process while it runs in parallel but then you would need to monitor the status of the process i.e. is it still running or has it completed, and the availability of output.

    0 讨论(0)
提交回复
热议问题