700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Java将文件夹生成压缩包.zip文件【已解决】

Java将文件夹生成压缩包.zip文件【已解决】

时间:2020-04-07 01:09:50

相关推荐

Java将文件夹生成压缩包.zip文件【已解决】

【话不多说直接上代码,复制粘贴然后引入JDK的包即可使用】

import java.nio.file.Paths;public static final int BUFFER = 1024;//compress方法需要传入2个参数,是两个地址//第一个地址是目标打包文件的地址,第二个是zip包输出的地址public static void main(String[] args) throws IOException {String hallFilePath = "E:/" + "packs";compress(Paths.get(hallFilePath).toString(), hallFilePath + ".zip");}//由此开始是所有相关的工具方法public static void compress(String fromPath, String toPath) throws IOException {File fromFile = new File(fromPath);File toFile = new File(toPath);if (!fromFile.exists()) {throw new ExportException(fromPath + "不存在!");}try (FileOutputStream outputStream = new FileOutputStream(toFile); CheckedOutputStream checkedOutputStream = new CheckedOutputStream(outputStream, new CRC32()); ZipOutputStream zipOutputStream = new ZipOutputStream(checkedOutputStream)) {String baseDir = "";compress(fromFile, zipOutputStream, baseDir);}}private static void compress(File file, ZipOutputStream zipOut, String baseDir) throws IOException {if (file.isDirectory()) {compressDirectory(file, zipOut, baseDir);} else {compressFile(file, zipOut, baseDir);}}private static void compressFile(File file, ZipOutputStream zipOut, String baseDir) throws IOException {if (!file.exists()) {return;}try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {ZipEntry entry = new ZipEntry(baseDir + file.getName());zipOut.putNextEntry(entry);int count;byte[] data = new byte[BUFFER];while ((count = bis.read(data, 0, BUFFER)) != -1) {zipOut.write(data, 0, count);}}}private static void compressDirectory(File dir, ZipOutputStream zipOut, String baseDir) throws IOException {File[] files = dir.listFiles();if (files != null && ArrayUtils.isNotEmpty(files)) {for (File file : files) {compress(file, zipOut, baseDir + dir.getName() + File.separator);}}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。