欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

压缩一个目录下的所有文件但不压缩子目录,压缩一个目录,压缩一个目录下的所有文件

来源: javaer 分享于  点击 49983 次 点评:178

压缩一个目录下的所有文件但不压缩子目录,压缩一个目录,压缩一个目录下的所有文件


压缩一个目录下的所有文件但不压缩子目录

ZipTest.java

package test2;import java.io.*;import java.nio.charset.*;import java.util.zip.*;public class ZipTest {    public static void main(String[] args) {        FileOutputStream fos = null;        ZipOutputStream zipOut = null;        File[] files = new File("D:\\WebExpert").listFiles();        File f=new File("D:\\WebExpert.zip");        try {            fos = new FileOutputStream(f);            zipOut = new ZipOutputStream(fos,Charset.forName("GBK"));        } catch (FileNotFoundException e1) {            e1.printStackTrace();            f.delete();            return;        }        for (int i = 0; i < files.length; i++) {            if (files[i].isFile()) {                FileInputStream fis = null;                try {                    fis = new FileInputStream(files[i]);                    ZipEntry entry = new ZipEntry(files[i].getName());                    zipOut.putNextEntry(entry);                    int nNumber;                    byte[] buffer = new byte[Integer.MAX_VALUE/32];                    while ((nNumber = fis.read(buffer)) != -1)                        zipOut.write(buffer, 0, nNumber);                    zipOut.flush();                } catch (IOException e) {                    e.printStackTrace();                    try {                        zipOut.close();                        fos.close();                        f.delete();                    } catch (IOException e1) {                        e1.printStackTrace();                    }                    return;                } finally {                    try {                        fis.close();                    } catch (IOException e) {                    }                }            }        }        try {            zipOut.close();            fos.close();        } catch (IOException e) {            e.printStackTrace();        }    }}
相关栏目:

用户点评