读取目录下的文件将文件压缩

来源:互联网 发布:录音软件免费下载 编辑:程序博客网 时间:2024/06/05 16:55
/* * 将下载下来的文件打成压缩包 * documentPath    原文件目录 * resultPath   结果文件名 */ public String compression(String documentPath,String resultPath){        OutputStream outStream;    ZipOutputStream zos = null;    File file = new File(documentPath);    try {        outStream = new FileOutputStream(resultPath);        zos = new ZipOutputStream(outStream);// 将输入流获取的信息存储到zip的输出流里面        //读取目录中的所有文件        String[] list = file.list();        String[] filenames = new String[list.length];        for (int i = 0; i < list.length; i++) {            if ("".equals(list[i]))                continue;            filenames[i] = resultPath + list[i];        }        // 定义 数组大小        // int bufferSize = 1024 * 10 * 10;        byte[] b = new byte[102400];        int len = 0;        for (int i = 0; i < filenames.length; i++) {            File tFile = new File(filenames[i]);            if (!tFile.exists())                continue;            String shortName = tFile.getName();            zos.putNextEntry(new ZipEntry(shortName));            FileInputStream inStream = new FileInputStream(filenames[i]);            BufferedInputStream BuffedInStream = new BufferedInputStream(inStream);            while ((len = BuffedInStream.read(b)) != -1) {                zos.write(b, 0, len);            }            zos.flush();            inStream.close();            BuffedInStream.close();        }        deleteCatalogAndFiles(documentPath);//删除目录    }catch(Exception e) {        logger.error("压缩文件时出错", e);    }finally {        try {            zos.close();        } catch (IOException e) {            logger.error("关闭流出错", e);        }    }    return resultPath;}/* * 删除文件目录下的文件及目录 */public void deleteCatalogAndFiles(String documentPath){    File file = new File(documentPath);    if (file.isDirectory()){        String[] children = file.list();//文件夹目录列表        for (String child : children)        {            deleteCatalogAndFiles(documentPath+ "//" + child);        }    }    file.delete();}
0 0