java - BufferedReader.readLine blocks my program but BufferedReader.read() reads properly -


i have snippet follows:

process proc = runtime.getruntime().exec(command); bufferedreader br = new bufferedreader(new inputstreamreader(proc.geterrorstream())); string line = br.readline(); 

now in above code sure process have on line input, did not use kind of while loop or null check. problem readline blocks. 1 reason aware of is, stream having no data read , hence readline keeps waiting. check this, removed readline , used read() function follows:

process proc = runtime.getruntime().exec( command ); bufferedreader br = new bufferedreader(new inputstreamreader(proc.geterrorstream())); int a; while((a=br.read())!=-1){     char ch = (char) a;     if(ch == '\n')         system.out.print("new line "+ch);     if(ch == '\r')         system.out.print("carriage return "+ch);     system.out.print(ch); } 

to surprise code worked , printed messags new line , carriage return. wondering why did readline block? data available terminated newline. else reason??

note: above worked once in while! maybe once out of 15times.
note: tried using processbuilder too, same behaviour.

update: switched processbuilder , redirected errorstream , both input stream , error stream @ once when process.getinputstream , works fine. below snippet.

processbuilder pb = new processbuilder(command.split(" ")); pb..redirecterrorstream(true); process proc = pb.start(); bufferedreader br = new bufferedreader(new inputstreamreader(proc.getinputstream())); string line = br.readline(); //now both input , error stream. 

i differentiate error stream input stream method jumbled up! ideas on this?

so avoid getting error stream , input stream merged remove line pb.redirecterrorstream(true);

because said in java doc :

if property true, error output generated subprocesses subsequently started object's start() method merged standard output, both can read using process.getinputstream() method. makes easier correlate error messages corresponding output. initial value false.

by calling pb.redirecterrorstream(true); merging both output.


Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -