You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@commons.apache.org by Arun Ramakrishnan <ar...@languageweaver.com> on 2009/09/24 01:06:06 UTC

[exec] Piping to Input Stream using PipedInputStream

I am trying to build java wrapper around a binary. The idea is that I can stream in and out of this binary that has heavy startup time.

1)      I used to be able to achieve this using ProcessBuilder ( refer to code snippet 1 )

2)      I trying to use Apache Commons Exec instead to start the binaries ( it see from the code that it has separate threads to deal with the various streams so that the binary dosent block due to full output or error buffers ). But, it  seems extremely complicated to open a stream/pipe to the input of the binary. I am not sure if Code snippert 2 is the right approach to it using Piped Streams classes.

3)      One of the problems I am having is that I don't understand why the pipe seems to close prematurely after only one write to it. Please refer to code snippet 3 for a concise code that demonstrates the problem I am having.

Any suggestions would be appreciated.

######################## Code Snippet 1 ##############################

Process p = "tool.exe".execute()  // uses processBuilder
BufferedOutputStream pout = new BufferedOutputStream( p.getOutputStream() )

// then use pout to send input to the tool.exe's input stream

########################  Code Snippet 3 ##############################

PipedOutputStream ps = new PipedOutputStream();
PipedInputStream is = new PipedInputStream(ps);
BufferedWriter os = new BufferedWriter(new OutputStreamWriter(ps));
String s = "hi there \n hi \n";
[1..1000].each{
println it
os.write(s);
}
os.close();
println is.getText();

######################## Code Snippet 2 ################################
import org.apache.commons.exec.*;

String line = "F:\\Suggester\\bin\\langid.bat" ;
String infile = "F:\\Suggester\\bin\\in.txt" ;
CommandLine commandLine = CommandLine.parse(line);


commandLine.addArgument("engita")
DefaultExecutor executor = new DefaultExecutor();
FileInputStream fis = new FileInputStream( infile )
PipedOutputStream ps = new PipedOutputStream();
PipedInputStream is = new PipedInputStream(ps);
PrintStream os = new PrintStream(ps);
String s = "hi there \n--#--\nwhatup";
[1..1000].each{
println it
os.append(s);
os.flush();
}
os.close();
println is.getText()
PumpStreamHandler ioh = new PumpStreamHandler(System.out,System.err,is);
//ioh.setProcessInputStream(System.out) his will not work
ioh.start()
executor.setStreamHandler(ioh)
//pis.write( s.getBytes() );
int exitValue = executor.execute(commandLine);
println " execution started"
println exitValue;

####################### End ##########################################