commons-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Siegfried Goeschl <siegfried.goes...@it20one.at>
Subject Re: [exec]How could I use exec to execute a java program with keyboard input in it?
Date Wed, 28 Sep 2011 19:08:17 GMT
Hi,

if I understand that correctly you would like to get some keyboard input 
for your child process - I have never done that but I think the 
following snippet from DefaultExecutorTest might show you the way

Cheers,

Siegfried Goeschl

     /**
      * The test script reads an argument from <code>stdin<code> and prints
      * the result to stdout. To make things slightly more interesting
      * we are using an asynchronous process.
      *
      * @throws Exception the test failed
      */
     public void testStdInHandling() throws Exception {

         ByteArrayInputStream bais = new 
ByteArrayInputStream("Foo".getBytes()); // newline not needed; causes 
problems for VMS
         CommandLine cl = new CommandLine(this.stdinSript);
         PumpStreamHandler pumpStreamHandler = new PumpStreamHandler( 
this.baos, System.err, bais);
         DefaultExecuteResultHandler resultHandler = new 
DefaultExecuteResultHandler();
         Executor executor = new DefaultExecutor();
         executor.setStreamHandler(pumpStreamHandler);
         executor.execute(cl, resultHandler);

         resultHandler.waitFor(WAITFOR_TIMEOUT);
         assertTrue("ResultHandler received a result", 
resultHandler.hasResult());

         assertFalse(exec.isFailure(resultHandler.getExitValue()));
         String result = baos.toString();
         assertTrue("Result '"+result+"' should contain 'Hello Foo!'", 
result.indexOf("Hello Foo!") >= 0);
     }


On 27.09.11 09:41, Yi Huang wrote:
> For example:
>
> import java.util.Scanner;
>
> public class ToBeCalled {
>
> public static void main(String[] args) {
> Scanner keyboard = new Scanner(System.in);
> int t = keyboard.nextInt();
> System.out.println(t);
> }
> }
>
> How could I use exec to let it run properly?
> I have tried this:
>
> // compile
> cmdline = CommandLine.parse("javac");
> executor = new DefaultExecutor();
> cmdline.addArgument("ToBeCalled.java");
> exitValue = executor.execute(cmdline);
> System.out.println("compile: " + exitValue);
>
> // run
> cmdline = CommandLine.parse("java");
> cmdline.addArgument("ToBeCalled");
> cmdline.addArgument("abc");
> cmdline.addArgument("def");
> executor = new DefaultExecutor();
> exitValue = executor.execute(cmdline);
> System.out.println("run: " + exitValue);
>
> It did compile, but crashed and said that there is no argument in nextInt()
> How could I fix that?
>

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@commons.apache.org
For additional commands, e-mail: user-help@commons.apache.org


Mime
View raw message