0

I have this code which is working fine. How to send my input to the Java Process Builder?

Here is the code:

PrintStream out = System.out;
Runtime rt = Runtime.getRuntime(); 
try {
     out.println("Executing a command in a separate process...");
     Scanner input = new Scanner(System.in);
     String str = input.nextLine();
     Process proc = rt.exec(str);

     /*OutputStream procIn = proc.getOutputStream();
     procIn.write("My Code".getBytes());
     procIn.close();*/

     InputStream procOut = proc.getInputStream();
     byte[] msgOut = new byte[64];
     int len = procOut.read(msgOut);
     procOut.close();
     out.println("Output from the command: "
        +new String(msgOut,0,len));

     out.println("Waiting for the process to finish...");
     int rc = proc.waitFor();
     out.println("Status code returned by the process "+rc);
  } catch (Exception e) {
     e.printStackTrace();
  }

I need to know how to use this section:

/*OutputStream procIn = proc.getOutputStream();
     procIn.write("My Code".getBytes());
     procIn.close();*/

Thanks in advance for any help.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Vahe
  • 96
  • 3
  • 2
    You'll want a separate thread that can write to the `OutputStream` of the process until `waitFor` exits... – MadProgrammer Jun 28 '13 at 08:50
  • Can you please send a working code about it..... – Vahe Jun 28 '13 at 08:56
  • 1
    Try [this](http://stackoverflow.com/questions/15260426/how-to-use-exitvalue-with-parameter/15262005#15262005), don't forget to send money ;) – MadProgrammer Jun 28 '13 at 08:59
  • 1
    Read (and implement) *all* the recommendations of [When Runtime.exec() won't](http://www.javaworld.com/jw-12-2000/jw-1229-traps.html). That might solve the problem. If not, it should provide more information as to the reason it failed. Then ignore that it refers to `exec` and build the `Process` using a `ProcessBuilder`. Also break a `String arg` into `String[] args` to account for arguments which themselves contain spaces. – Andrew Thompson Jun 28 '13 at 08:59

0 Answers0