How to estimate zip file size in java before creating it

后端 未结 7 421
时光取名叫无心
时光取名叫无心 2021-01-08 00:27

I am having a requirement wherein i have to create a zip file from a list of available files. The files are of different types like txt,pdf,xml etc.I am using java util clas

相关标签:
7条回答
  • 2021-01-08 01:28

    There is a better option. Create a dummy LengthOutputStream that just counts the written bytes:

    public class LengthOutputStream extends OutputStream {
    
        private long length = 0L;
    
        @Override
        public void write(int b) throws IOException {
            length++;
        }
    
        public long getLength() {
            return length;
        }
    }
    

    You can just simply connect the LengthOutputStream to a ZipOutputStream:

    public static long sizeOfZippedDirectory(File dir) throws FileNotFoundException, IOException {
            try (LengthOutputStream sos = new LengthOutputStream();
                ZipOutputStream zos = new ZipOutputStream(sos);) {
                ... // Add ZIP entries to the stream
                return sos.getLength();
            }
        }
    

    The LengthOutputStream object counts the bytes of the zipped stream but stores nothing, so there is no file size limit. This method gives an accurate size estimation but almost as slow as creating a ZIP file.

    0 讨论(0)
提交回复
热议问题