How to estimate zip file size in java before creating it

后端 未结 7 428
时光取名叫无心
时光取名叫无心 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:24

    Wrap your ZipOutputStream into a personalized OutputStream, named here YourOutputStream.

    • The constructor of YourOutputStream will create another ZipOutputStream (zos2) which wraps a new ByteArrayOutputStream (baos)
      public YourOutputStream(ZipOutputStream zos, int maxSizeInBytes)
    • When you want to write a file with YourOutputStream, it will first write it on zos2
      public void writeFile(File file) throws ZipFileFullException
      public void writeFile(String path) throws ZipFileFullException
      etc...
    • if baos.size() is under maxSizeInBytes
      • Write the file in zos1
    • else
      • close zos1, baos, zos2 an throw an exception. For the exception, I can't think of an already existant one, if there is, use it, else create your own IOException ZipFileFullException.

    You need two ZipOutputStream, one to be written on your drive, one to check if your contents is over 5MB.

    EDIT : In fact I checked, you can't remove a ZipEntry easily.

    http://download.oracle.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html#size()

提交回复
热议问题