I am trying to run java code dynamically in my java application GUI. I have tried the following code:
Sring tempfile="java -classpath "+wrkdir+"/bin "+runfile;
CommandLine cmdLine = CommandLine.parse(tempfile);
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
DefaultExecutor executor = new DefaultExecutor();
executor.setExitValue(1);
executor.setWatchdog(watchdog);
try {
executor.execute(cmdLine, resultHandler);
} catch (ExecuteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
resultHandler.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The result is, when my input file (tempfile) consisting of printing statements; that is,
public class Sample2 {
public static void main(String[] args) {
System.out.println("It Works..!!");
}
}
it is able to display the results. But if the input file is something like,
import java.io.DataInputStream;
import java.io.IOException;
import java.util.*;
public class Count
{
public static void main(String args[]) throws IOException
{
int n;
System.out.println("Enter the number: ");
DataInputStream din=new DataInputStream(System.in);
String s=din.readLine();
n=Integer.parseInt(s);
System.out.println("#"+n);
}
}
a NumberFormatException is the result. What is the reason for this? How can I input values through keyboard in this case?
Did you consider that your parseInt in the input file may actually be throwing a legitimate parse exception?
Try changing the following line
to
The
DefaultExector()
constructor doesn't attach to standard input, so you are not getting any input, and there is nothing to parse. To attach to standard input, create an ExecuteStreamHandler and add it to your DefaultExecutor like this:If you want to read your input from somewhere else instead of System.in, pass a suitable InputStream object to the PumpStreamHandler constructor.