1. Don't use scanner when transferring data between an InputStream and an OutputStream. There is no need for any kind of conversion. Read binary byte array and write the same.
2. When redirecting program stdin its a good practice to close the input of the program when you don't want to send more input to it.
3. Use PipedOutputStream/PipedInputStream to create a "channel" to simulate input.
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintWriter;
class Program
{
private final Process proc;
private final Thread out, err, in;
public Program(String cmd, OutputStream pOut, OutputStream pErr, InputStream pIn) throws IOException
{
proc = Runtime.getRuntime().exec(cmd);
out = new Transfert(proc.getInputStream(), pOut, false);
err = new Transfert(proc.getErrorStream(), pErr, false);
in = new Transfert(pIn, proc.getOutputStream(), true);
System.out.println("le output de lapplication ="+ out);
System.out.println("le input de lapplication ="+ in);
System.out.println("l'erreur de lapplication ="+ err);
out.start();
err.start();
in.start();
}
public void kill()
{
out.interrupt();
err.interrupt();
in.interrupt();
proc.destroy();
}
}
class Transfert extends Thread
{
private final InputStream in;
private final OutputStream out;
private boolean closeOutput;
public Transfert(InputStream in, OutputStream out, boolean closeOutput)
{
this.in = in;
this.out = out;
this.closeOutput = closeOutput;
}
@Override
public void run()
{
try
{
byte[] buf = new byte[0x100];
do
{
int len = in.read(buf);
if (len < 0)
break;
out.write(buf, 0, len);
out.flush();
}
while (!isInterrupted());
}
catch (IOException e)
{
System.err.println(e);
}
finally
{
if (closeOutput)
{
try
{
out.close();
}
catch (IOException ex) {}
}
}
}
}
public class Test
{
public static void main(String[] args) throws Exception
{
PipedInputStream pipedInput = new PipedInputStream();
PipedOutputStream pipedOutput = new PipedOutputStream(pipedInput);
Program prog = new Program("C:\\Division.exe", System.out, System.err, pipedInput);
PrintWriter pw = new PrintWriter(pipedOutput);
pw.println("5");
pw.println("2");
pw.close();
}
}