【问题标题】:Reading byte[] from BufferedInputStream从 BufferedInputStream 中读取 byte[]
【发布时间】:2019-04-26 15:56:30
【问题描述】:

想知道下面从 TCP Socket 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() 的调用将返回 0)。这可能是对available() 方法的滥用,因为通常不建议使用available() 返回的值来确定要读入的缓冲区的大小。

标签: java bufferedinputstream


【解决方案1】:

您不应该依赖调用available() 来找出流的长度,因为它只返回估计值。如果要读取所有字节,请在这样的循环中执行:

String data = "";
byte[] buffer = new byte[1024];
int read;
while((read = _in.read(buffer)) != -1) {
   data += new String(buffer, 0, read);    
} 

【讨论】:

  • 最好使用StringBuilder。此外,还有 InputStream.readAllBytes() 可以为您提供所有字节而无需编写循环,但不幸的是仅从 Java 9 开始可用。
【解决方案2】:

您可以使用 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;

【讨论】:

  • 但是原来的方法没有跳过任何字节。
  • 我问错了。我需要读取所有字节。我想以更简单的方式做到这一点,而不使用int s = _in.read(); 行。我也想知道使用这条线的原因是什么。
猜你喜欢
  • 1970-01-01
  • 2022-01-16
  • 2017-05-05
  • 1970-01-01
  • 2019-05-27
  • 1970-01-01
  • 1970-01-01
  • 2014-02-01
  • 2017-05-06
相关资源
最近更新 更多