关于下面从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;
}发布于 2019-04-27 00:36:05
您不应该依赖调用available()来找出流的长度,因为它只返回估计值。如果你想读取所有的字节,就像这样在一个循环中完成:
String data = "";
byte[] buffer = new byte[1024];
int read;
while((read = _in.read(buffer)) != -1) {
data += new String(buffer, 0, read);
} 发布于 2019-04-27 00:07:34
您可以使用BufferedInputStream的skip方法跳过任意大小的字节。就像你可以添加到你的代码中,如下所示
_in.skip(1);
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;https://stackoverflow.com/questions/55871164
复制相似问题