FileOutputStream 未正确写入非 .txt 文件

FileOutputStream not properly writing non-.txt files

出于某种原因,我的 FileOutputStream 只能正确写入 .txt 格式的文件。字节是通过 UDP 从另一台服务器接收的,但它是通过本地主机接收的,所以我认为数据包不会丢失。任何人都可以看到什么会导致非 .txt 字节写得不好吗?您认为问题可能出在发送字节的服务器上吗?如果它来自发送服务器,我会感到惊讶,因为它为 .txt 文件写入了正确的字节。

public class CompressionServer {

private static final int ECHOMAX = 65535;  // Maximum size of UDP packet

public static void main(String[] args) throws IOException {

    int servPort = Integer.parseInt(args[0]);

    DatagramSocket socket = new DatagramSocket(servPort);
    DatagramPacket packet = new DatagramPacket(new byte[ECHOMAX], ECHOMAX);

    for (;;) {  // Run forever, receiving and echoing datagrams
        socket.receive(packet);
        byte[] data = packet.getData();
        String fileName = new String(data, 0, packet.getLength());

        FileOutputStream fout = new FileOutputStream(fileName.trim()); //unzipped file output
        FileOutputStream fout2 = new FileOutputStream(fileName.trim() + ".zip"); //zipped file output
        ZipOutputStream zout = new ZipOutputStream(fout2); //I guess this writes zip bytes to fout2?

        ZipEntry entry = new ZipEntry(fileName.trim()); //call the entry in the zip file "proj3.bin"
        zout.putNextEntry(entry); //the next entry our ZipOutputStream is going to write is "proj3.bin"

        while(true) {
            socket.receive(packet);
            data = packet.getData();
            String magicString = new String(data, 0, packet.getLength(), "US-ASCII");
            int index = magicString.indexOf("--------MagicStringCSE283Miami");
            if(index != -1){
                fout.write(data, 0, index);
                fout.flush();
                fout.close();

                zout.write(data, 0, index); //write the byteBuffer's data to the client via the zip output stream
                zout.flush(); //push all data out of the zipOutputStream before continuing
                fout2.flush();
                zout.close();
                fout2.close();
                break;
            }
            //System.out.println("packet received");
            fout.write(packet.getData(), 0, packet.getLength());
            fout.flush();

            zout.write(data, 0, packet.getLength()); //write the byteBuffer's data to the client via the zip output stream
            zout.flush(); //push all data out of the zipOutputStream before continuing
            fout2.flush();
        }   
    }
    //socket.close();
}
/* NOT REACHED */
}

FileOutputStream not properly writing non-.txt files

FileOutputStream当然不是问题。你告诉它写什么,它就写什么。但是,在到达 FileOutputStream:

附近之前,您可以通过多种方式破坏数据
  1. 您没有显示发送码。
  2. String 不是二进制数据的容器。
  3. 'From another server'和'over the localhost'是相互矛盾的,它们都不能保证UDP数据报的传递,或者不重复,或者顺序。如果没有基于 ACK 或 NACK 的协议,这将无法正常工作。
  4. UDP 数据报的最大有效负载 大小为 65507 字节,这仍然非常不切实际。公认的可用最大为 534 字节。
  5. 在已经刷新或关闭zout时刷新并关闭fout2是多余的,关闭前刷新zout也是多余的。