由于某种原因,我的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 */
}
答案 0 :(得分:1)
FileOutputStream未正确编写非.txt文件
FileOutputStream
当然不是问题。它会写出你要写的任何内容。但是,在获得FileOutputStream:
String
不是二进制数据的容器。fout2
时刷新和关闭zout
是多余的,在关闭之前刷新zout
也是多余的。