英文:
Byte Array through Input Stream
问题
我正在处理客户端和服务器之间的文件/图像发送和接收。我使用来自Socket的InputStream。
这段代码:
byte[] sizeAr = new byte[4];
int num = inputStream.read();
sizeAr = ByteBuffer.allocate(4).putInt(num).array();
int size = ByteBuffer.wrap(sizeAr).asIntBuffer().get();
与这段代码是否相同:
byte[] sizeAr = new byte[4];
inputStream.read(sizeAr);
int size = ByteBuffer.wrap(sizeAr).asIntBuffer().get();
英文:
I am working on client-server sending and receiving of files/images. I use inputstream from a Socket.
Is this code
byte[] sizeAr = new byte[4];
int num = inputStream.read();
sizeAr = ByteBuffer.allocate(4).putInt(num).array();
int size = ByteBuffer.wrap(sizeAr).asIntBuffer().get();
same as this code
byte[] sizeAr = new byte[4];
inputStream.read(sizeAr);
int size = ByteBuffer.wrap(sizeAr).asIntBuffer().get();
答案1
得分: 1
这段代码[...] 和这段代码是否相同?
不相同。
对于第一个代码段,我感到有些费解:
- 分配了一个 4 字节的数组(没有任何原因?)
- 从流中读取 一个字节
- 创建了一个新的 4 字节缓冲区,
- 将上一行中读取的字节作为整数放入缓冲区,
- 获取缓冲区的支持数组,替换了第一行中的数组
- 用新的字节缓冲区包装了上一个缓冲区中的数组,
- 将其转换为整数缓冲区
- 从此缓冲区获取整数,并将此整数赋值给
size
基本上,这是一种非常复杂且低效的方式,相当于执行了
int size = inputStream.read();
我认为这可能不是你想要的。
第二个代码段更有意义:
- 分配了一个 4 字节的数组
- 从输入流中最多读取 4 个字节到数组中(注意应该检查
read(byte[])
的返回值,以获取实际读取的字节数,可能会比数组大小小) - 将数组包装在缓冲区中,
- 将其转换为整数缓冲区
- 获取值作为整数,并将其赋值给
size
这个版本将会把一个完整的 32 位整数值读入 size
中,这可能是你想要的。然而,第 2 步并不安全,因为你可能会读取少于 4 个字节,正如前面提到的。
也许,一个更好的方式是使用类似于:
DataInput dataInput = new DataInputStream(inputStream);
int size = dataInput.readInt(); // 将会精确地读取 4 个字节,或抛出 EOFException 异常
英文:
> Is this code [...] same as this code?
No.
The first one does not make much sense to me:
- allocates a 4 byte array (for no reason?)
- reads a single byte from the stream
- creates a new 4 byte buffer,
- puts the byte read in the previous line into the buffer as an int,
- gets the backing array of the buffer, replacing the array in the first line
- wraps the array from the previous buffer in a new byte buffer,
- converts it to an int buffer
- gets the int from this buffer, and assigns this int to
size
Basically, this is a very convoluted an inefficient way of doing
int size = inputStream.read();
I don't think this is what you want.
The second one makes more sense:
- allocates a 4 byte array
- reads up to 4 bytes from the input stream into the array (note that you should check the return value of
read(byte[])
, to get the number of bytes read, it may be less than the size of your array) - wraps the array in a buffer,
- converts it to an int buffer
- gets the value as an int and assigns it to
size
This version will read a full 32 bit int value into size
, which is probably what you want. However, step 2 is not safe, as you may read less than 4 bytes as mentioned.
Probably, a better way would be to use something like:
DataInput dataInput = new DataInputStream(inputStream);
int size = dataInput.readInt(); // Will read exactly 4 bytes or throw EOFException
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论