我有从网络输入流读取的方法。
//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));”排除空字节?
最佳答案
您的读取逻辑有问题,因为您分配了一个 1024 的缓冲区(所有成员都初始化为 null),然后在最后一次传递时,显然缓冲区的某些部分可以保持为空,从而导致写入 null 值。
因此,一旦到达流末尾,您需要停止阅读,请尝试按照以下方式更改代码:
byte[] buff = new byte[255];
String output = "";
InputStream is = //get input stream
int n = 0;
while ( (n = is.read(buff) )!=-1)
{
output += new String(buff,0,n);
}
is.close();
这样,您将获得仅包含初始化缓冲区成员的字符串,“n”的值是实际读取的字节数(=无空值)。您可以根据需要更改读取 block 。
关于java从带有缓冲区的网络输入流中读取(需要排除空符号),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19681369/