简体   繁体   中英

BufferedOutputStream not writing everything to file

I trying to create a TFTP server but when it receives a file it seems that not all of it is saved on to the server (some bytes are missing). The file is created fine and the majority of data is written but as the file is not complete it is classed as corrupt and unopenable. Does anyone know how to fix this issue?

main class

            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);

WRQ class

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;

}

}

This code looks very suspicious to me:

byte[] packetData = packet.getData();
byte[] data = new byte[length - 4];
data = Arrays.copyOfRange(packetData, 4, length - 4);

Your output array (data) is of length length - 4 , but you only copy length - 8 bytes to it. If the bytes to ignore in packetData are the first 4 bytes, it should be

data = Arrays.copyOfRange(packetData, 4, length);

because the last argument is not a length, but the to index (exclusive). See the javadoc for details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM