Java 通过输入流的字节数组
我正在处理发送和接收文件/图像的客户端服务器。我使用来自套接字的inputstream 这是密码吗Java 通过输入流的字节数组,java,arrays,image,sockets,client-server,Java,Arrays,Image,Sockets,Client Server,我正在处理发送和接收文件/图像的客户端服务器。我使用来自套接字的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]; in
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();
与此代码相同
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();
此代码[…]与此代码相同吗
没有
第一个对我来说没有多大意义:
- 将前一行中读取的字节作为int放入缓冲区
- 获取缓冲区的备份数组,替换第一行中的数组
- 将其转换为int缓冲区
- 从该缓冲区获取int,并将该int分配给
size
int size = inputStream.read();
我认为这不是你想要的。:-)
第二个更有意义:
read(byte[])
的返回值,以获取读取的字节数,它可能小于数组的大小)- 将其转换为int缓冲区
- 以int形式获取值并将其分配给
size
大小
,这可能是您想要的。但是,第2步并不安全,因为您可能会像前面提到的那样读取少于4个字节
也许,更好的方法是使用以下内容:
DataInput dataInput = new DataInputStream(inputStream);
int size = dataInput.readInt(); // Will read exactly 4 bytes or throw EOFException
不,两者都错了。您正在查找
DataInputStream.readInt()
,后跟readFully()
。