如何对单个文件进行简单的zip压缩

java中有zip包,里面有ZipInputStream, ZipOutputStream类,我们只要把文件读入,然后使用ZipOutputStream输出就可以了,ZipOutputStream输出时按ZipEntry为单位的,java对单个文件的简单压缩可以看下面的例子:

package com.tjcyjd.commons;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 将单个文件进行压缩
 * @author yjd
 */
public class FileCompress {

    public static void zip(String inName, String outName){
        File file = new File(inName);
        int length = (int) file.length();
        byte[] b = new byte[length];
        try {
            InputStream in = new FileInputStream(file);
            in.read(b );
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(new File(outName)));
            zout.setLevel(9);
            ZipEntry zipEntry = new ZipEntry(file.getName());
            zout.putNextEntry(zipEntry);
            zout.write(b);
            zout.finish();
            zout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        String inName = "D:/yjd.txt";
        String outName = "D:/yjd.zip";

        FileCompress.zip(inName, outName);
    }

}

zout.setLevel(9)是设置压缩等级,参数为0-9 0为不压缩,9为压缩最厉害,如果对效率没什么要求,而对体积要求比较高,可以设置为9。



你可能感兴趣的:(java,exception,String,File,Class,byte)