栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将文件添加到ZIP文件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将文件添加到ZIP文件

您不能压缩文件夹,只能压缩文件。要压缩文件夹,必须手动添加所有子文件。我写了本课来完成这项工作。您可以免费获得它:)

用法是这样的:

List<File> sources = new ArrayList<File>();sources.add(tobackup);Packager.packZip(new File(zipName), sources);

这是课程:

import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.List;import java.util.zip.Deflater;import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;public class Packager{    public static void packZip(File output, List<File> sources) throws IOException    {        System.out.println("Packaging to " + output.getName());        ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(output));        zipOut.setLevel(Deflater.DEFAULT_COMPRESSION);        for (File source : sources)        { if (source.isDirectory()) {     zipDir(zipOut, "", source); } else {     zipFile(zipOut, "", source); }        }        zipOut.flush();        zipOut.close();        System.out.println("Done");    }    private static String buildPath(String path, String file)    {        if (path == null || path.isEmpty())        { return file;        } else        { return path + "/" + file;        }    }    private static void zipDir(ZipOutputStream zos, String path, File dir) throws IOException    {        if (!dir.canRead())        { System.out.println("Cannot read " + dir.getCanonicalPath() + " (maybe because of permissions)"); return;        }        File[] files = dir.listFiles();        path = buildPath(path, dir.getName());        System.out.println("Adding Directory " + path);        for (File source : files)        { if (source.isDirectory()) {     zipDir(zos, path, source); } else {     zipFile(zos, path, source); }        }        System.out.println("Leaving Directory " + path);    }    private static void zipFile(ZipOutputStream zos, String path, File file) throws IOException    {        if (!file.canRead())        { System.out.println("Cannot read " + file.getCanonicalPath() + " (maybe because of permissions)"); return;        }        System.out.println("Compressing " + file.getName());        zos.putNextEntry(new ZipEntry(buildPath(path, file.getName())));        FileInputStream fis = new FileInputStream(file);        byte[] buffer = new byte[4092];        int byteCount = 0;        while ((byteCount = fis.read(buffer)) != -1)        { zos.write(buffer, 0, byteCount); System.out.print('.'); System.out.flush();        }        System.out.println();        fis.close();        zos.closeEntry();    }}

请享用!

编辑 :要检查程序是否仍在忙,可以添加我用(*)标记的三行

编辑2 :尝试新的代码。在我的平台上,它运行正确(OS X)。我不确定,但是在Windows中,AppData中的文件可能会有一些有限的读取权限。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/569527.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号