第一句子网 - 唯美句子、句子迷、好句子大全
第一句子网 > Java将指定文件/文件夹压缩成zip rar压缩文件--解決中文乱码

Java将指定文件/文件夹压缩成zip rar压缩文件--解決中文乱码

时间:2018-09-22 14:28:24

相关推荐

Java将指定文件/文件夹压缩成zip rar压缩文件--解決中文乱码

参考:/itzgs/article/details/31776259

一、压缩工具类

package com.xxxx.utils;import org.apache.tools.zip.ZipEntry;import org.apache.tools.zip.ZipOutputStream;import java.io.*;import java.util.zip.CheckedOutputStream;import java.util.zip.CRC32;/**** 将指定文件/文件夹压缩成zip、rar压缩文件*/public class ZipCompressor {/*** 默认构造函数*/public ZipCompressor() {}/*** @param resourcesPath 资源文件夹* @param targetPath 目的压缩文件保存路径* @param targetName 压缩包文件名称* @return void* @throws Exception* @desc 将源文件/文件夹生成指定格式的压缩文件,格式zip*/public void compressedFile(String resourcesPath, String targetPath,String targetName) throws Exception {File resourcesFile = new File(resourcesPath); File targetFile = new File(targetPath); if (!targetFile.exists()) {targetFile.mkdirs();}FileOutputStream outputStream = new FileOutputStream(targetPath + "/" + targetName+".zip");CheckedOutputStream cos = new CheckedOutputStream(outputStream, new CRC32());ZipOutputStream out = new org.apache.tools.zip.ZipOutputStream(cos);createCompressedFile(out, resourcesFile, "");out.close();}/*** @param out 输出流* @param file 目标文件* @return void* @throws Exception* @desc 生成压缩文件。* 如果是文件夹,则使用递归,进行文件遍历、压缩* 如果是文件,直接压缩*/public void createCompressedFile(ZipOutputStream out, File file, String dir) throws Exception {//如果当前的是文件夹,则进行进一步处理if (file.isDirectory()) {//得到文件列表信息File[] files = file.listFiles();//将文件夹添加到下一级打包目录out.putNextEntry(new ZipEntry(dir + "/"));dir = dir.length() == 0 ? "" : dir + "/";//循环将文件夹中的文件打包for (int i = 0; i < files.length; i++) {createCompressedFile(out, files[i], dir + files[i].getName());}} else { //当前的是文件,打包处理//文件输入流BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));ZipEntry entry = new ZipEntry(dir);out.setEncoding("GBK");out.putNextEntry(entry);// out.putNextEntry(new ZipEntry(dir));//进行写操作int j = 0;byte[] buffer = new byte[1024];while ((j = bis.read(buffer)) > 0) {out.write(buffer, 0, j);}//关闭输入流bis.close();}}}

二、测试代码

@Testvoid ziptest(){String sourceFilePath = "D:\\file\\photo\\\\01\\30";ZipCompressor zipCompressor = new ZipCompressor();try {pressedFile(sourceFilePath, "F:\\test\\zip","464646");System.out.println("压缩文件已经生成...");} catch (Exception e) {System.out.println("压缩文件生成失败...");e.printStackTrace();}}

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