我可以将java byte[]缓冲区绑定到InputStream并多次读取吗?



我可以绑定readBuf到DataInputStream,我将读取一些字节到readBuf,我将读取int和其他数据从DataInputStream绑定到readBuf。我可以做下面的代码吗?

byte[] readBuf = new byte[MAX_BYTE_SIZE ];
DataInputStream dis = new DataInputStream(new ByteArrayInputStream(readBuf));
writeBytes( UartCmd[1] );
i_ReadLength = readBytes(readBuf);
uc_Index = dis.readInt();
writeBytes( i_WritedLength );
i_ReadLength = readBytes(readBuf);
uc_Index = dis.readInt();

感谢你的帮助。

我建议java.nio.ByteBuffer

    ...
    uc_Index = ByteBuffer.wrap(readBuf).getInt();
    writeBytes( i_WritedLength );
    i_ReadLength = readBytes(readBuf);
    uc_Index = ByteBuffer.wrap(readBuf).getInt();

你已经"绑定"了一个字节[]缓冲区到一个输入流:

DataInputStream dis = new DataInputStream(new ByteArrayInputStream(readBuf));

这应该与dis.readInt();一起工作。在它上面循环你希望在缓冲区中有多少个int。

我不能告诉你readBytes()writeBytes()会发生什么,因为你还没有定义它们。名称i_ReadLength的含义似乎与我期望的名为readBytes()的方法返回的含义完全不同。你的编译器不会在乎,但我们人类在乎。

如果你希望能够查看readBuf内部并告诉你有多少int类型被添加到它上面,你可能要失望了。int型字节数组不会像字符串那样以空结束。你必须跟踪有多少readBuf已经在某个地方用整数初始化了,否则你最终会读到垃圾(从未写过的数据,可能有任何值)。

你可以做的是让字节数组中的第一个整型作为数组中所有其他整型的计数。一旦你读了这个,你就知道要循环多少次了。请确保在编写时将其设置为正确的值。另外,不要写入太多的int,以免字节数组溢出。记住,字节和整型是不同大小的。

如果这就是你所做的,不要重新发明轮子。这样做:

byte[] readBuf = getSizePrefixedByteArrayOfInts();
DataInputStream dis = new DataInputStream(new ByteArrayInputStream(readBuf));
//writeBytes( UartCmd[1] ); //Seriously, I've no idea what this does
int i_ReadLength = dis.readInt();
int[] readInts = new int[i_ReadLength];
for(int i = 0; i < i_ReadLength; i++) {
    readInts[i] = dis.readInt();
}

理解这里的关键是,这段代码期望长度计数器本身不被计数。如果计数器是缓冲区中唯一初始化的int类型,那么它的值应该为0。下面是测试代码:

private byte[] getSizePrefixedByteArrayOfInts() {
  ByteArrayOutputStream baos = null;
  DataOutputStream dos = null;
  int[] buf = {65, 66, 67, 68, 69, 70, 71};
  try{
     // create byte array output stream
     baos = new ByteArrayOutputStream();
     // create data output stream
     dos = new DataOutputStream(baos);
     // write number of other ints in array
     dos.write(buf.length); 
     // write to the stream from integer array
     for(int i: buf)
     {
        dos.write(i);
     }
     // flushes bytes to underlying output stream
     dos.flush();
     return baos.toByteArray();
  }catch(Exception e){
     // if any error occurs
     e.printStackTrace();
  }finally{
     // releases all system resources from the streams
     if(baos!=null)
        baos.close();
     if(dos!=null)
        dos.close();
  }
}

我感谢教程点的大块getSizePrefixedByteArrayOfInts()代码。

最新更新