capture error from runtime process java

微笑、不失礼 提交于 2020-03-23 04:05:53

问题


I'm running a Java program from another Java application using Runtime.getRuntime().exec like this

Process p1 = Runtime.getRuntime().exec("javac test.java");
Process p2 = Runtime.getRuntime().exec("java test");

The content of the test.java

import java.io.*;
class test
{
 public static void main(String args[])
  {
  Scanner sc = new Scanner(System.in);
  String s = sc.nextLine();
  System.out.println(s);
  }
}

I want to handle Input, Output and Error stream of the process p2. I did capture of the output of the test.java, however, I do not know how to handle output and error.

Here is my code:

try {
    String s = "";
    InputStream istr = p2.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(istr));
    BufferedReader bre = new BufferedReader
        (new InputStreamReader(p2.getErrorStream()));

    while ((s = br.readLine()) != null) {
        System.out.println(s);
    }
    br.close();
    while ((s = bre.readLine()) != null) {
        System.out.println(s);
    }
    bre.close();
    p2.waitFor();
} catch (IOException ex) {
    ex.printStackTrace();
} catch (Exception err) {
    err.printStackTrace();
}

The code above works fine for capturing the output of the test.java. But it does not display error of the test.java.

Could you please give me a sample code for fixing this problem and handling output stream or share idea? Thanks in advance


回答1:


The solution I've always used is to create a separate thread to read one of the streams

So, in your case it should be something like

String s = "";
InputStream istr = p2.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(istr));
BufferedReader bre = new BufferedReader
        (new InputStreamReader(p2.getErrorStream()));


new Thread(new Runnable() {    
    @Override
    public void run() {
       while ((s = br.readLine()) != null) {
             System.out.println(s);
        }
     }
 }).start();

 new Thread(new Runnable() {    
    @Override
    public void run() {
         while ((s = bre.readLine()) != null) {
              System.out.println(s);
          }
     }
  }).start();
// when you are finished close streams


来源:https://stackoverflow.com/questions/11795145/capture-error-from-runtime-process-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!