`
午刀十
  • 浏览: 34115 次
  • 性别: Icon_minigender_1
  • 来自: 厦门
社区版块
存档分类
最新评论

Java文件压缩

    博客分类:
  • java
阅读更多
/**
 * 之所以用org.apache.tools.zip包而不用java.util.zip包,是由于后者对中文不能正常解析
 */

package otherTest;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

public class ZipTest
{

    public static void main(String[] args) throws Exception
    {
        try
        {
            List<String> sourceFileNames = new ArrayList<String>();
            sourceFileNames.add("c:\\1.docx"); //要压缩的文件1
            sourceFileNames.add("c:\\2.txt");//要压缩的文件2
            zipFiles("c:\\3.zip", sourceFileNames);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    /**
     * zip压缩. 将指定文件集合压缩后存到一压缩文件中
     * 
     * @author: xujp1
     * @param sourceFileNames 所要压缩的文件名集合
     * @param zipFilename 压缩后的文件名
     * @return 压缩后文件的大小
     * @throws Exception
     */
    public static void zipFiles(String zipFilename, List<String> sourceFileNames) throws Exception
    {
        File objFile = new File(zipFilename);
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(objFile));
        for(String sourceFileName : sourceFileNames)
        {
            File sourceFile = new File(sourceFileName);
            byte[] buf = new byte[1024];
            //压缩文件名
            ZipEntry ze = null;
            //创建一个ZipEntry,并设置Name和其它的一些属性
            ze = new ZipEntry(sourceFile.getName());
            ze.setSize(sourceFile.length());
            ze.setTime(sourceFile.lastModified());
            //将ZipEntry加到zos中,再写入实际的文件内容
            zos.setEncoding("gbk");
            zos.putNextEntry(ze);
            InputStream is = new BufferedInputStream(new FileInputStream(sourceFile));
            int readLen = -1;
            while ((readLen = is.read(buf, 0, 1024)) != -1)
            {
                zos.write(buf, 0, readLen);
            }
            is.close();
        }
        zos.close();
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics