我有从网络输入流中读取的方法。
//pattern value is shell prompt string ":~#"
//this do read shells output like from command "ls", etc...
public String readUntil(String pattern) throws IOException, JSchException {
long began = System.currentTimeMillis();
long lastTime = System.currentTimeMillis();
StringBuilder sb = new StringBuilder();
socket.setTimeout(timeout);
iks: while (true) {
try {
int c = -1;
byte[] text = new byte[1024];
c = in.read(text);
long now = System.currentTimeMillis();
if (c != -1) {
sb.append(new String(text));
lastTime = now;
}
if (now - lastTime > timeout){
System.out.println( "BREAK BY TIMEOUT");
break;
}
if (sb.toString().contains(pattern)) {
System.out.println( "BREAK BY PATTERN");
break;
}
Thread.sleep(50);
}catch(Exception e){
System.out.println("¬"+e);
break iks;
}
}
System.out.println( "TIME TAKEN readUntil -> "+(System.currentTimeMillis()-began));
//Log.v("¬","result -> "+sb.toString());
return sb.toString();
}
这工作得相当快,但每次读取都会用空值填充字节数组的末尾。如何做“sb.append(new String(text));” 不包括空字节?