2012-08-25 38 views
5

我在我的Java應用程序中下載了一些文件並實現了一個下載監視器對話框。但最近我用gzip壓縮了所有的文件,現在下載監視器有點壞了。監視器GZip下載Java中的進度

我將文件打開爲GZIPInputStream,並在每下載一次kB後更新下載狀態。如果該文件具有1MB的大小,則進展達到例如4MB這是未壓縮的大小。我想監視壓縮的下載進度。這可能嗎?

編輯:澄清:我正在讀取未壓縮字節的GZipInputStream中的字節。所以這最終沒有給我正確的文件大小。

這裏是我的代碼:

URL url = new URL(urlString); 
HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
con.connect(); 
... 
File file = new File("bibles/" + name + ".xml"); 
if(!file.exists()) 
    file.createNewFile(); 
out = new FileOutputStream(file); 
in = new BufferedInputStream(new GZIPInputStream(con.getInputStream())); 

byte[] buffer = new byte[1024]; 
int count; 
while((count = in.read(buffer)) != -1) { 
    out.write(buffer, 0, count); 
    downloaded += count; 
    this.stateChanged(); 
} 

... 

private void stateChanged() { 
    this.setChanged(); 
    this.notifyObservers(); 
} 

感謝您的幫助!

+0

我正在讀取由未壓縮流的'GZipInputStream'下載的字節。所以這不是真正的下載文件大小。 – dbrettschneider

+0

好吧,現在我明白了。 – SJuan76

回答

4

根據說明書,GZIPInputStreamInflaterInputStream的子類。 InflaterInputStream有一個protected Inflater inf字段,即用於解壓縮工作的InflaterInflater.getBytesRead應該對你的目的特別有用。

不幸的是,GZIPInputStream沒有公開inf,因此您可能需要創建自己的子類並公開Inflater,例如,

public final class ExposedGZIPInputStream extends GZIPInputStream { 

    public ExposedGZIPInputStream(final InputStream stream) { 
    super(stream); 
    } 

    public ExposedGZIPInputStream(final InputStream stream, final int n) { 
    super(stream, n); 
    } 

    public Inflater inflater() { 
    return super.inf; 
    } 
} 
... 
final ExposedGZIPInputStream gzip = new ExposedGZIPInputStream(...); 
... 
final Inflater inflater = gzip.inflater(); 
final long read = inflater.getBytesRead(); 
+0

謝謝!我只需要實現一個自定義的GZIPInputStream,使得'Inflater int'的'getBytesRead()'可用。 – dbrettschneider

+0

謝謝,這正是我一直在尋找的! –