APCoding
APCoding

Reputation: 301

Java Getting the Standard Output and Standard Error from a Seperate Process

I am starting a separate process in my Java program using ProcessBuilder This is were the process gets made:

Class klass=Program.class;
String[] output=new String[2];
 String javaHome = System.getProperty("java.home");
 String javaBin = javaHome +
         File.separator + "bin" +
         File.separator + "java";
 String classpath = System.getProperty("java.class.path");
 String className = klass.getCanonicalName();

 ProcessBuilder builder = new ProcessBuilder(
         javaBin, "-cp", classpath, className);

 Process process = builder.start();
 process.waitFor();

Program.class is the following:

public class Program {
public static void main(String[] args) {
System.out.println("Hi!");
}

I want the standard output to produce Hi!, and the standard error, if I were to, for example, not add a semicolon after System.out.println("Hi!") then the standard error would be:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Syntax error, insert ";" to complete BlockStatements

at Program.main(Program.java:6)

So, how can I do this? Ideally, the program converts these into two strings.

Thanks

Upvotes: 1

Views: 2670

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347314

Start by taking a closer look at the Process class, it has an inputStream property, which is attached to the processes stdout. You can also use ProcessBuilder to redirect the stderr through the stdout to make life easier, using ProcessBuilder#redirectErrorStream(boolean)

You can write to the Process using its outputStream property (try not to think about it to much)...

Basically, you want to "read" the "output", via the inputStream and "write" to the "input" via the outputStream

Something like...

Class klass=Program.class;
String[] output=new String[2];
String javaHome = System.getProperty("java.home");
String javaBin = javaHome +
     File.separator + "bin" +
     File.separator + "java";
String classpath = System.getProperty("java.class.path");
String className = klass.getCanonicalName();

ProcessBuilder builder = new ProcessBuilder(
     javaBin, "-cp", classpath, className);
builder.redirectErrorStream(true);

Process process = builder.start();
int in = -1;
InputStream is = process.getInputStream();
try {
    while ((in = is.read()) != -1) {
        System.out.println((char)in);
    }
} catch (IOException ex) {
    ex.printStackTrace();
}
int exitCode = process.waitFor();
System.out.println("Exited with " + exitCode);

as an example

Upvotes: 2

Related Questions