2016-03-24 34 views
0

我使用的是GZIPOutputStream的GZIP類的圖像。我嘗試通過OutputStream發送GZIP文件時收到損壞的文件。我知道如何將GZIP轉換爲FileOutputStream。下面的代碼工作完美:如何在Java上通過GZIP文件並通過OutputStream發送它

Static private void GZIPCompress(String fileName) 
{ 
     File file = new File(fileName); 
     FileInputStream fis = new FileInputStream(file); 
     byte[] data = new byte[(int) file.length()]; 

     fis.read(data); 
     FileOutputStream fos = new FileOutputStream(fileName + ".gz"); 
     GZIPOutputStream gzos = new GZIPOutputStream(fos); 
     gzos.write(data); 
     fos.close(); 
     fis.close(); 
} 

輸出文件是myfile.png.gz並具有以下細節

myfile.png.gz:gzip壓縮的數據,從FAT文件( MS-DOS,OS/2, NT)

我的問題是,當我嘗試GZIP文件並將其發送到的OutputStream。由於我正在使用服務器,因此我正在從服務器調用此服務器,並使用套接字。

Static void SendGZIPFile(String fileName, OutputStream os) 
{ 
     DataOutputStream dos = new DataOutputStream(os); 
     File file = new File(fileName); 
     FileInputStream fis = new FileInputStream(file); 
     byte[] data = new byte[(int) file.length()]; 
     byte[] dataAux = new byte[(int) file.length()]; 
     dos.writeBytes("HTTP/1.1 200 OK\r\n"); 
     dos.writeBytes("Content-Type: application/x-gzip \r\n"); 
     dos.writeBytes("Content-Disposition: form-data; filename="+"\""+fileName+".gz"+"\""+"\n"); 
     dos.writeBytes("\r\n\r\n"); 
     dos = new DataOutputStream(new GZIPOutputStream(os)); 
     fis.read(data); 
     dos.write(data); 
     dos.close(); 
     fis.close(); 
     gzos.close(); 
} 

我得到的是沒有包含任何損壞的GZIP文件:這裏是細節

myfile.gz數據

我覺得我做錯了什麼而GZipping,因爲我注意到詳細信息之間的差異。我用下面的命令來得到它:file myfile.gz

+0

只是出於興趣,你爲什麼要手工做HTTP,而不是使用庫/框架? – RAnders00

+0

PNG已經被壓縮,所以試圖GZIP它可能會使它更大。 –

+0

你能否也請顯示調用'SendGZIPFile(fileName,outputStream)'的部分? – RAnders00

回答

1

Flush gzos在關閉之前dos。首先關閉gzos

+0

請注意,我的問題是與第二個函數sendGZIPFiles,我沒有變量gzos。 –

+0

對不起,'gzos.close();'confused me –

+0

你的行結束符似乎很腥,嘗試刪除內容處置行中的\ n。 –

1

除了你的代碼缺乏基本的正確性(你可能不應該在你的代碼中實現HTTP,過去更聰明的人已經這樣做),我認爲問題是你沒有正確地複製數據。相反,你應該在一個循環做複製這樣的:

byte[] buf = new byte[1024]; 
int len; 
while((len = fis.read(buf)) != -1) 
{ 
    dos.write(buf, 0, len); 
} 

或者你可以只使用Apache下議院IO:

IOUtils.copy(fis, dos); 
+0

我試過了,但它返回相同的文件。沒有數據和損壞.. –