2011-05-13 13 views
1

私は、圧縮オブジェクトをファイルに書き込むコードを書いていました。私の質問は、書き込まれているオブジェクトのファイルサイズの増分を追跡できる方法はありますか?ここに私のコードは次のとおりです。java:実行時のファイルサイズの追跡を続けますか?

public static void storeCompressedObjs(File outFile, ArrayList<Object[]> obj) { 
    FileOutputStream fos = null; 
    GZIPOutputStream gz = null; 
    ObjectOutputStream oos = null; 
    try { 
     fos = new FileOutputStream(outFile); 
     gz = new GZIPOutputStream(fos); 
     oos = new ObjectOutputStream(gz); 
     for (Object str : obj) { 
      oos.writeObject(str); 
      oos.flush(); 
      //I was hoping to print outFile.length() here, but it doesn't work 
     } 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     oos.close(); 
     gz.close(); 
     fos.close(); 
    } 
} 

私はすべてのoos.writeObject(str);flushを使用して、outFile.length()を使用してファイルサイズを取得しようとしましたが、私はそれをフラッシュどんなに、ファイルのサイズは、その最後のジャンプまで変わりません最終サイズ。とにかく私はそれを修正することができますか?ありがとう

答えて

1

Apache CommonsプロジェクトにはCountingOutputStreamというクラスがあり、OutputStreamのチェーンに入れることができます。あなたも、それらのうちの2つを持つことができます。

package so5997784; 

import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.ObjectOutputStream; 
import java.io.OutputStream; 
import java.util.zip.GZIPOutputStream; 

import org.apache.commons.io.output.CountingOutputStream; 

public class CountBytes { 

    private static void dump(File outFile, Object... objs) throws IOException { 
    FileOutputStream fos = new FileOutputStream(outFile); 
    try { 
     CountingOutputStream compressedCounter = new CountingOutputStream(fos); 
     OutputStream gz = new GZIPOutputStream(compressedCounter); 
     CountingOutputStream uncompressedCounter = new CountingOutputStream(gz); 
     ObjectOutputStream oos = new ObjectOutputStream(uncompressedCounter); 

     for (Object obj : objs) { 
     oos.writeObject(obj); 
     oos.flush(); 
     System.out.println(uncompressedCounter.getByteCount() + " -> " + compressedCounter.getByteCount()); 
     } 
     oos.close(); 
     System.out.println(uncompressedCounter.getByteCount() + " -> " + compressedCounter.getByteCount()); 

    } finally { 
     fos.close(); 
    } 
    } 

    public static void main(String[] args) throws IOException { 
    File outFile = new File("objects.out.gz"); 
    dump(outFile, "a", "b", "cde", "hello", "world"); 
    } 

} 
+0

私はメソッドを呼び出したとき、私は '8を得た - > 10 12 - > 10 18 - > 10 26 - > 10 34 - > 10 34 - > 51'そこに5 10人いるのはなぜですか?増やしてはいけませんか? – user685275

+0

とにかく、これは私が欲しいものを達成しました。ありがとうございました。 – user685275

+0

これは、 'GZIPOutputStream.flush()' *は出力をフラッシュせず、多少の圧縮レベルを保証しているか、それ。 –

関連する問題