BufferedOutputStream no escribe todo en el archivo
-
12-12-2019 - |
Pregunta
Intento crear un servidor TFTP pero cuando recibe un archivo parece que no todo está guardado en el servidor (faltan algunos bytes).El archivo se crea correctamente y la mayoría de los datos se escriben, pero como el archivo no está completo, se clasifica como corrupto y no se puede abrir.¿Alguien sabe cómo solucionar este problema?
clase principal
WRQ WRQ = new WRQ();
ACK ACK = new ACK();
DatagramPacket outPacket;
BufferedOutputStream bufferedOutput = new BufferedOutputStream(new FileOutputStream(filename));
byte[] bytes;
byte[] fileOut;
outPacket = WRQ.firstPacket(packet);
socket.send(outPacket);
socket.receive(packet);
while (packet.getLength() == 516){
bytes = WRQ.doWRQ(packet);
bufferedOutput.write(bytes);
outPacket = ACK.doACK(packet);
socket.send(outPacket);
socket.receive(packet);
}
bytes = WRQ.doWRQ(packet);
bufferedOutput.write(bytes);
bufferedOutput.close();
outPacket = ACK.doACK(packet);
socket.send(outPacket);
clase WRQ
public class WRQ {
public DatagramPacket firstPacket(DatagramPacket packet) throws IOException{
ACK ACK = new ACK();
DatagramPacket ACKpacket = ACK.doACK(packet);
//takes ACK packet and sets block # as 0 to signal that this is the first packet in a WRQ
byte[] ACKcontents = new byte[3];
ACKcontents = ACKpacket.getData();
ACKcontents[2] = 0;
ACKcontents[3] = 0;
ACKpacket.setData(ACKcontents);
return ACKpacket;
}
public byte[] doWRQ(DatagramPacket packet){
int length = packet.getLength();
byte[] packetData = packet.getData();
byte[] data = new byte[length - 4];
data = Arrays.copyOfRange(packetData, 4, length - 4);
return data;
}
}
Solución
Este código me parece muy sospechoso:
byte[] packetData = packet.getData();
byte[] data = new byte[length - 4];
data = Arrays.copyOfRange(packetData, 4, length - 4);
Su matriz de salida (datos) es de longitud length - 4
, pero solo copias length - 8
bytes a él.Si los bytes a ignorar en paquetes de datos son los primeros 4 bytes, debería ser
data = Arrays.copyOfRange(packetData, 4, length);
porque el último argumento no es una longitud, sino el to
índice (exclusivo).Ver el javadoc para detalles.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow