【问题标题】:java: keep tracking of file size on the run?java:在运行时跟踪文件大小?
【发布时间】:2011-08-25 06:18:26
【问题描述】:

我编写了一个将压缩对象写入文件的代码,我的问题是:有没有一种方法可以跟踪写入对象时文件大小的增量?这是我的代码:

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() 获取文件大小,但是无论我刷新多少,文件大小都保持不变,直到最后一次跳转到最终大小。无论如何我可以解决它?谢谢

【问题讨论】:

    标签: java io size compression objectoutputstream


    【解决方案1】:

    Apache Commons 项目提供了一个类CountingOutputStream,您可以将其放入OutputStreams 链中。您甚至可以拥有其中两个:

    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");
      }
    
    }
    

    【讨论】:

    • 我在调用方法的时候得到8 -&gt; 10 12 -&gt; 10 18 -&gt; 10 26 -&gt; 10 34 -&gt; 10 34 -&gt; 51为什么那里有5个10s,不应该是递增的吗?
    • 无论如何,这实现了我想要的,非常感谢您的帮助
    • 这是因为GZIPOutputStream.flush()刷新其输出,可能是为了保证一定的压缩级别或因为文件格式不允许这样做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-10
    • 2010-12-29
    • 2011-08-24
    • 2011-06-17
    • 1970-01-01
    • 2018-09-17
    • 1970-01-01
    相关资源
    最近更新 更多