想知道下面从 TCP 套接字 BufferedInputStream 读取数据的代码。是否有任何原因使用 int s = _in.read()
读取第一个字节,然后使用 _in.read(byteData);
读取其余字节。我可以只读取 byte[] 而不使用第一个读取行吗?
private static String readInputStream(BufferedInputStream _in) throws IOException
{
String data = "";
int s = _in.read();
if(s==-1)
return null;
data += ""+(char)s;
int len = _in.available();
System.out.println("Len got : "+len);
if(len > 0) {
byte[] byteData = new byte[len];
_in.read(byteData);
data += new String(byteData);
}
return data;
}
最佳答案
您不应依赖调用 available()
来找出 Stream 的长度,因为它仅返回估计值。如果您想读取所有字节,请在如下循环中执行:
String data = "";
byte[] buffer = new byte[1024];
int read;
while((read = _in.read(buffer)) != -1) {
data += new String(buffer, 0, read);
}
关于java - 从 BufferedInputStream 读取 byte[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55871164/