我有从联网的输入流中读取的方法。
//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(新的字符串(文本));” 排除空字节?
尝试BufferedInputStream
在您的代码中使用->BufferedInputStream(InputStream in)
and方法read(byte[] b, int off, int len)
从给定的偏移量开始,将字节输入流中的字节读取到指定的字节数组中,并返回读取的字节数;如果已到达流的末尾,则返回-1。
在您的代码中它将是:
BufferedInputStream bis = new BufferedInputStream(in);
...
byte text[] = new byte[]; // size of byte array can change
c = bis.read(text, 0, 1024);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句