BufferedReader.readLine() do not read and hang the

2019-03-03 09:43发布

问题:

BufferedReader.readLine() do not read and hang the system(wait).

InputStream istrm = runtimeProcess.getInputStream();
InputStreamReader istrmrdr = new InputStreamReader(istrm);
BufferedReader buffrdr = new BufferedReader(istrmrdr);
System.out.println("4");
String data;
String st;
System.out.println("4a");
while (!(st=buffrdr.readLine()).isEmpty()) {
    System.out.println("5 in loop");
}

回答1:

You need to continually read from the processes input stream to ensure that it doesn't block.

Read this : http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html



回答2:

The point is this line

while (!(st=buffrdr.readLine()).isEmpty())

Your code will wait for the line to terminate. That is, till it finds "\n" character; It will keep buffering and hence will not come out of loop. So either in the input stream manage to have quick lines. Or read through bytes. You should probably read bytes and work along.

int i=0;
char[] buf = new char[10000]
while((i=buffrdr.read(buf,i,100))!= -1)
{
 String h = new String(buf);
 //use h o print accordingly.