我正在创建一个 TFTP 服务器。我可以很好地传输文件,但是大多数文件到达另一端时都不会打开。这是因为 ArrayList 的输出用于存储接收到的每个数据包的文件字节,将字节负载添加到文件的开头。例如。“¬í sr java.util.ArrayListxÒ™Ça I sizexp w ur [B¬óøTà xp ü!”。首先使用列表的原因是我创建的服务器无法告诉正在接收的文件的文件大小。因此,据我所知,我不能使用 byte[] 因为它需要用设定的长度进行初始化。有没有办法解决这个问题?
WRQ WRQ = new WRQ();
ACK ACK = new ACK();
DatagramPacket outPacket;
byte[] bytes;
byte[] fileOut;
List fileBytes = new ArrayList();
outPacket = WRQ.firstPacket(packet);
socket.send(outPacket);
socket.receive(packet);
while (packet.getLength() == 516){
bytes = WRQ.doWRQ(packet);
fileBytes.add(bytes);
outPacket = ACK.doACK(packet);
socket.send(outPacket);
socket.receive(packet);
}
bytes = WRQ.doWRQ(packet);
fileBytes.add(bytes);
outPacket = ACK.doACK(packet);
socket.send(outPacket);
ObjectOutputStream os;
ByteArrayOutputStream byteStream = new ByteArrayOutputStream(5000);
os = new ObjectOutputStream(new BufferedOutputStream(byteStream));
os.flush();
os.writeObject(fileBytes);
os.flush();
byte[] outFile = byteStream.toByteArray();
os.close();
FileOutputStream foStream = new FileOutputStream(filename);
foStream.write(outFile);
foStream.close();