Hi everyone!
I'm creating a program that will compile and run another java program:
Lets say I have a program in directory
D:\HelloWorld\src
and compiled program will be in
D:\HelloWorld\bin
inside src and bin is a folder hello (that's a package)
This program will be run by another program (that's the program that I am creating)
Here is the code of my program:
package runnercompiler; import java.io.IOException; import java.io.InputStream; import java.util.logging.Level; import java.util.logging.Logger; public final class RunnerCompiler { public static void main(String[] args) throws IOException, InterruptedException { RunnerCompiler compiler = new RunnerCompiler(); String command = "javac -d D:\\HelloWorld\\bin D:\\HelloWorld\\src\\hello\\HelloWorld.java"; ProcessBuilder processBuilder = new ProcessBuilder("cmd", "/c", command); Process process = processBuilder.start(); OutStreamAccumulator out = compiler.new OutStreamAccumulator(process.getInputStream()); out.start(); /* to make sure that the other thread will finish compile the HelloWorld first before doing next statement */ out.join(); command = "java -classpath D:\\HelloWorld\\bin hello.HelloWorld"; // running the HelloWorld processBuilder = new ProcessBuilder("cmd", "/c", command); process = processBuilder.start(); out = compiler.new OutStreamAccumulator(process.getInputStream()); out.start(); out.join(); } private class OutStreamAccumulator extends Thread { private InputStream inStream; public OutStreamAccumulator(InputStream inStream) { this.inStream = inStream; } @Override public void run() { try { int value; while ((value = inStream.read()) != -1) { System.out.print((char) value); } } catch (IOException ex) { Logger.getLogger(RunnerCompiler.class.getName()).log(Level.SEVERE, null, ex); } } } }
That works fine.
and it will print:
Hello World
Hello World
Problem
The problem is, how can I get the error messages that will occur
if the program crashes because of exception?
or the program falls into catch and the catch block prints
the error using stackTrace or Logger?
Below code is example of my problem:
Lets say I edited my HelloWorld program:
Obviously, it caught an exception at line 9package hello; public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); System.out.println("Hello World"); try { Integer.parseInt("a"); // line 9 } catch (NumberFormatException ex) { ex.printStackTrace(); System.out.println("Error"); } System.out.println("Done"); } }
when my RunnerCompiler program runs, it prints
Hello World
Hello World
Error
Done
Well, it didn't printed out the exception error.
I hope someone knows how to get that exception message..
Thanks a lot