views:

59

answers:

1
+1  Q: 

Java.lang.Runtime

Hi folks,

I have a piece of code that invokes an instance of the bash terminal through the use of the following --

proc = Runtime.getRuntime().exec("/bin/bash", null, working-dir);

and then to run unix commands on this invoked instance of bash I'm using a PrintWriter object like this --

PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);

I'm then using the PrintWriter object to actually execute the commands in the following fashion--

out.println("pwd");
out.println("ls >a.txt");

While both of the commands seem to work perfectly fine, I have an issue in the case wherein I construct a command based on some user input. Being specific, I'm constructing a command to send some files to a printer on the network and I'm doing it like this --

while ((strLine = br.readLine()) != null)   {
cmd= blah +blah +blah;//Construction of the command
out.println(cmd);
}

What is actually happening in the above piece of code is that br is reading from a file which contains all the files that need to be printed and then the string having the file name goes into the command and I write it onto the PrintWriter object.

the issue Im facing is that , I guess there some sort of queuing that's happening and the PrintWriter object is not actually passing on the command to the invoked bash instance every time a command is constructed. So at the end of the day, if there are 40 commands that are being constructed, only about 16-18 documents are being printed. I guess it it because it is sending all the commands to the printer in one go resulting in the loss.I want to eliminate this loss.

Any pointers ??

Thanks p1nG

+1  A: 

Try putting an out.flush() in your loop. This will flush the buffer in the BufferedWriter that you created.

Another tip may be to avoid trying use a single bash exec for all of the commands and instead construct and execute the command individually. Consider using Process Builder instead of Runtime.exec().

Michael Barker