本文介绍了如何在创建之前估计java中的zip文件大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我有一个要求,我必须从可用文件列表中创建一个zip文件。这些文件有不同的类型,如txt,pdf,xml等。我正在使用java util类来完成它。



此处的要求是保持文件的最大大小为5 mb。我应该根据时间戳从列表中选择文件,将文件添加到zip,直到zip文件大小达到5 mb。我应该跳过剩下的文件。



如果在java中有一种方法可以提前估算zip文件大小而不创建实际文件,请告诉我?



还是有其他方法来处理这个

解决方案

包裹你的将ZipOutputStream转换为个性化的OutputStream,在此命名为YourOutputStream。




  • YourOutputStream的构造函数将创建另一个(zos2)包装一个新的(baos)

    public YourOutputStream(ZipOutputStream zos,int maxSizeInBytes)

  • 当你想用 YourOutputStream 写一个文件时,它会先在zos2上写一个


    public void writeFile(File file)throws ZipFileFullException

    public void writeFile(String path)throws ZipFileFullException

    等......

  • 如果在 maxSizeInBytes $下b
    $ b

    • 将文件写入zos1


  • else


    • 关闭zos1,baos,zos2抛出异常。对于异常,我想不出已经存在的,如果存在,请使用它,否则创建自己的IOException ZipFileFullException。




您需要两个ZipOutputStream,一个要写在您的驱动器上,一个用于检查您的内容是否超过5MB。



你无法轻易删除ZipEntry 。




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 classes to do it.

The requirement here is to maintain a maximum file size of 5 mb. I should select the files from list based on timestamp, add the files to zip until the zip file size reaches 5 mb. I should skip the remaining files.

Please let me know if there is a way in java where in i can estimate the zip file size in advance without creating actual file?

Or is there any other approach to handle this

解决方案

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()

这篇关于如何在创建之前估计java中的zip文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 14:01