简体   繁体   English

BufferedOutputStream没有将所有内容写入文件

[英]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). 我试图创建一个TFTP服务器,但是当它接收到文件时,似乎并不是所有文件都保存到了服务器上(有些字节丢失了)。 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 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;

}

}

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. 您的输出数组(数据)的长度为length - 4 ,但您仅将length - 8复制length - 8个字节。 If the bytes to ignore in packetData are the first 4 bytes, it should be 如果packetData中要忽略的字节是前4个字节,则应为

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

because the last argument is not a length, but the to index (exclusive). 因为最后一个参数不是长度,而是to索引(不包括)。 See the javadoc for details. 有关详细信息,请参见javadoc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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