Thursday, 15 January 2015

linux - Java Process cannot get the InputStream through Runtime.getRunTime().exec() -



linux - Java Process cannot get the InputStream through Runtime.getRunTime().exec() -

try { string str; process process = runtime.getruntime().exec("bash /home/abhishek/workspace/pro/run"); inputstream isout = process.getinputstream(); inputstreamreader isoutr = new inputstreamreader(isout); bufferedreader brout = new bufferedreader(isoutr); while ((str = brout.readline()) != null) { system.out.println(str); } } grab (ioexception e) { e.printstacktrace(); }

the code has issues getting inputstream process, because if run shell script terminal runs fine, if run script this,the str null,

i using code output of shell script straight java instead writing script output in file

is there other way accomplish this,or how can issue solved using current approach

i think returned through error stream, can seek check process.geterrorstream().

you should wait created process prevent main programme completes before it. utilize process.waitfor();

public class testmain { private static final string bash_cmd = "bash"; private static final string prog = "/home/abhishek/workspace/pro/run"; private static final string[] cmd_array = { bash_cmd , prog }; public static void main(string[] args) { new thread(new runnable() { public void run() { bufferedreader reader = new bufferedreader(new inputstreamreader( system.in)); string command = null; seek { while ((command = reader.readline()) != null) { system.out.println("command received:" + command); } } grab (exception ex) { ex.printstacktrace(); // failed listening command } } }).start(); process process = null; seek { processbuilder processbuilder = new processbuilder(cmd_array); process = processbuilder.start(); inputstream inputstream = process.getinputstream(); setupstreamgobbler(inputstream, system.out); inputstream errorstream = process.geterrorstream(); setupstreamgobbler(errorstream, system.err); system.out.println("never returns"); process.waitfor(); } grab (ioexception e) { throw new runtimeexception(e); } grab (interruptedexception e) { throw new runtimeexception(e); } } public static void setupstreamgobbler(final inputstream is, final printstream ps) { final inputstreamreader streamreader = new inputstreamreader(is); new thread(new runnable() { public void run() { bufferedreader br = new bufferedreader(streamreader); string line = null; seek { while ((line = br.readline()) != null) { ps.println("process stream: " + line); } } grab (ioexception e) { e.printstacktrace(); } { seek { br.close(); } grab (ioexception e) { e.printstacktrace(); } } } }).start(); } }

java linux shell runtime bufferedreader

No comments:

Post a Comment