[英]FileOutputStream not properly writing non-.txt files
由於某種原因,我的FileOutputStream僅正確寫入.txt格式的文件。 這些字節是通過UDP從另一台服務器接收的,但是它是通過localhost接收的,因此我認為數據包不會丟失。 誰能看到導致非.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無法正確寫入非.txt文件
FileOutputStream
肯定不是問題。 它會寫出您要寫的內容。 但是,在到達FileOutputStream:
附近的任何地方之前,有太多方法可以破壞數據FileOutputStream:
String
不是二進制數據的容器。 zout
時刷新和關閉fout2
是多余的,在關閉之前刷新zout
也是多余的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.