我有一个类Packet
,我编写该类是为了填充516个字节的byte[]
数组。 packetNum
(short
)2,authKey
(short
)2和audio
(byte[]
)512。在我的Packet
类内部,是一种将这些属性组合在一起以创建大小为516的byte[]
数组以发送给收件人的方法:
public byte[] toByteArray() {
byte[] fullArray = new byte[516];
ByteBuffer packetNumBuffer = ByteBuffer.allocate(2);
packetNumBuffer.putShort(this.packetNum);
byte[] packetNumArray = packetNumBuffer.array();
ByteBuffer authKeyBuffer = ByteBuffer.allocate(2);
authKeyBuffer.putShort(this.authKey);
byte[] authKeyArray = authKeyBuffer.array();
System.arraycopy(packetNumArray, 0, fullArray, 0, packetNumArray.length);
System.arraycopy(authKeyArray, 0, fullArray, packetNumArray.length, authKeyArray.length);
System.arraycopy(this.audio, 0, fullArray, authKeyArray.length, this.audio.length);
return fullArray;
}
现在,当测试接收到的数据包时,我的packetNum
(在创建下一个Packet
之前递增)已成功传输-但是,authKey
和audio
完全错误。这是我的代码的输出,它使用Packet
和short authKey = 10
创建一个新的short packetNum = 0
:
Packet number: 0
Auth key = -7936
Packet number: 1
Auth key = 19201
Packet number: 2
Auth key = 31490
Packet number: 3
Auth key = -1
Packet number: 4
Auth key = -2
Packet number: 5
Auth key = -3
Packet number: 6
Auth key = -4
Packet number: 7
Auth key = -3
Packet number: 8
Auth key = -2
Packet number: 9
Auth key = -1
Packet number: 10
Auth key = 8192
当所有数据包都应为10
时,auth密钥会为每个数据包吐出随机数。这使我相信我的方法未按预期填充fullArray
。谁能发现我做错了什么?
答案 0 :(得分:2)
错误在这里
System.arraycopy(this.audio, 0, fullArray, authKeyArray.length, this.audio.length);
起始位置为authKeyArray.length
但是应该是authKeyArray.length + packetNumArray.length
无论如何,System.arraycopy
是绝对要避免的方法之一。
我的建议是,使用ByteArrayOutputStream
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(516);
outputStream.write(packetNumArray);
outputStream.write(authKeyArray);
outputStream.write(audio);
final byte[] fullArray = outputStream.toByteArray();
不是很多更优雅吗?