FileOutputStream没有正确编写非.txt文件

时间:2015-04-20 03:20:25

标签: java networking fileoutputstream

由于某种原因,我的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 */
}

1 个答案:

答案 0 :(得分:1)

  

FileOutputStream未正确编写非.txt文件

FileOutputStream当然不是问题。它会写出你要写的任何内容。但是,在获得FileOutputStream:

附近的任何地方之前,有太多方法可能损坏数据
  1. 您还没有显示发送代码。
  2. String不是二进制数据的容器。
  3. '来自其他服务器'并且通过本地主机'是相互矛盾的,它们都不能保证UDP数据报的传递,或非复制或排序。如果没有基于ACK或NACK的协议,这将无法正常工作。
  4. UDP数据报的最大有效负载大小为65507字节,这仍然是非常不切实际的。通常接受的可用最大值为534字节。
  5. 当您已经刷新或关闭fout2时刷新和关闭zout是多余的,在关闭之前刷新zout也是多余的。