【问题标题】:File compression server can only compress one file without being restarted文件压缩服务器只能压缩一个文件而无需重启
【发布时间】:2015-05-05 17:01:56
【问题描述】:

我已经调试了几天,但似乎找不到问题所在。此代码用于接收 UDP 数据包然后压缩字节以创建 zip 文件和解压缩文件的服务器。问题是它似乎适用于发送的第一个文件,但需要为任何其他文件重新启动。我猜我关闭了一些错误,但我似乎找不到它。

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

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

【问题讨论】:

    标签: java networking compression writing


    【解决方案1】:

    在进入无限循环之前创建输出流 (while(true))。在该循环中,您关闭了这些流,但您永远不会再次创建它们。

    我想,只需移动在循环内创建流的行即可解决您的问题。但请注意文件名。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-24
      • 1970-01-01
      • 1970-01-01
      • 2010-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-04
      相关资源
      最近更新 更多