Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a byte array to OutputStream of process builder (Java)

Tags:

java

io

iostream

byte[] bytes = value.getBytes();
Process q = new ProcessBuilder("process","arg1", "arg2").start();
q.getOutputStream().write(bytes);
q.getOutputStream().flush();
System.out.println(q.getInputStream().available());

I'm trying to stream file contents to an executable and capture the output but the output(InputStream) is always empty. I can capture the output if i specify the the file location but not with streamed input.

How might I overcome this?

like image 962
Arran McCabe Avatar asked Feb 25 '11 16:02

Arran McCabe


People also ask

Which method is used for writing bytes to an OutputStream in java?

Java OutputStream write(int b) Method The write(int b) method of OutputStream class is used to write the specified bytes to the output stream. The bytes to be written are the eight low-order bits of the argument b.

How do you create a byte array in java?

Convert byte[] array to File using Java In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file.

How do you write OutputStream in java?

Methods of OutputStreamwrite() - writes the specified byte to the output stream. write(byte[] array) - writes the bytes from the specified array to the output stream. flush() - forces to write all data present in output stream to the destination. close() - closes the output stream.


2 Answers

Try wrapping your streams with BufferedInputStream() and BufferedOutputStream():

http://download.oracle.com/javase/6/docs/api/java/lang/Process.html#getOutputStream%28%29

Implementation note: It is a good idea for the output stream to be buffered.

Implementation note: It is a good idea for the input stream to be buffered.

Even with buffered streams, it is still possible for the buffer to fill if you're dealing with large amounts of data, you can deal with this by starting a separate thread to read from q.getInputStream(), so you can still be reading from the process while writing to the process.

like image 66
Kevin K Avatar answered Sep 28 '22 19:09

Kevin K


Perhaps the program you execute only starts its work when it detects the end of its input data. This is normally done by waiting for an EOF (end-of-file) symbol. You can send this by closing the output stream to the process:

q.getOutputStream().write(bytes);
q.getOutputStream().close();

Try this together with waiting for the process.

like image 30
Philipp Wendler Avatar answered Sep 28 '22 17:09

Philipp Wendler