文件压缩工具类
解決了中文亂碼問題
導(dǎo)入apache的jar包
<dependency><groupId>org.apache.ant</groupId><artifactId>ant</artifactId><version>1.10.5</version> </dependency>代碼如下
package com.dist.util;import com.google.common.collect.Lists; import org.apache.commons.lang3.StringUtils; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory;import java.io.*; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Function; import java.util.zip.CRC32; import java.util.zip.CheckedOutputStream;/*** 壓縮文件 無中文亂碼問題* @author qyp* 2018-3-24 下午05:12:30*/ public class ZipUtils {private final static Logger logger = LoggerFactory.getLogger(ZipUtils.class);public static void main(String[] args) throws Exception {File rootFile = new File("E:\\temp\\test");List<InputStream> ins = new ArrayList<>();List<String> names = new ArrayList<>();List<String> namePaths = Lists.newArrayList();File[] list = rootFile.listFiles();for (File f : list) {names.add(f.getName());namePaths.add(f.getAbsolutePath());ins.add(new FileInputStream(f));}//zipByInStream("e:\\temp\\a.zip", ins, names);//zipByFileNames("e:\\temp\\a.zip", namePaths);zipByFiles("e:\\temp\\a.zip", Arrays.asList(list));}/*** 將文件的流集合代表的文件壓縮成一個(gè)壓縮包并保存到指定位置* @param savePath 生成的壓縮包的位置* @param inputStreams 文件流集合* @param names 文件名稱集合* @throws Exception 如果文件路徑不存在或者壓縮失敗,那么久會(huì)拋異常*/public static void zipByInStream(String savePath, List<InputStream> inputStreams, List<String> names) throws Exception {ZipOutputStream zos = getOutPutStream(savePath);BufferedReader bufr = null;// 緩存輸出流try (BufferedOutputStream out = new BufferedOutputStream(zos)) {for (int i = 0, len = inputStreams.size(); i < len; i++) {//添加一個(gè)條目到壓縮包zos.putNextEntry(new ZipEntry(names.get(i)));int c;// StandardCharsets.ISO_8859_1 防止文件內(nèi)容亂碼bufr = new BufferedReader(new InputStreamReader(inputStreams.get(i), StandardCharsets.ISO_8859_1));while ((c = bufr.read()) != -1) {out.write(c);}out.flush();if (bufr != null) {bufr.close();}}} catch (IOException r) {throw new RuntimeException("文件壓縮失敗");} finally {if (bufr != null) {bufr.close();}}}/*** 根據(jù)文件名集合獲取文件并壓縮* @param savePath 保存的壓縮文件路徑* @param targetFileNames 被壓縮的文件名集合(全路徑)* @throws Exception*/public static void zipByFileNames(String savePath, List<String> targetFileNames) throws Exception {Function<Object, String> nameFun = (obj) -> getFileName((String) obj);Function<Object, InputStream> inFun = (obj) -> {try {return new FileInputStream((String) obj);} catch (FileNotFoundException e) {e.printStackTrace();}return null;};zipFile(savePath, targetFileNames, nameFun, inFun);}/*** 根據(jù)文件集合生成壓縮文件* @param savePath 保存的壓縮文件路徑* @param targetFiles 被壓縮的文件集合* @throws Exception*/public static void zipByFiles(String savePath, List<File> targetFiles) throws Exception {Function<Object, String> nameFun = (obj) -> ((File)obj).getName();Function<Object, InputStream> inFun = (obj) -> {try {return new FileInputStream((File) obj);} catch (FileNotFoundException e) {e.printStackTrace();}return null;};zipFile(savePath, targetFiles, nameFun, inFun);}/*** 壓縮文件* @param savePath 保存的壓縮文件路徑* @param targets 被壓縮的對(duì)象(文件名集合(全路徑),或者文件集合)* @param nameFun 獲取文件名的Function對(duì)象* @param inFun 獲取InputStream的Function對(duì)象* @throws Exception*/private static void zipFile(String savePath, List<?> targets, Function<Object, String> nameFun, Function<Object, InputStream> inFun) throws Exception {ZipOutputStream zos = getOutPutStream(savePath);BufferedReader bufr = null;// 緩存輸出流try (BufferedOutputStream out = new BufferedOutputStream(zos)) {for (int i = 0, len = targets.size(); i < len; i++) {zos.putNextEntry(new ZipEntry(nameFun.apply(targets.get(i))));int c;bufr = new BufferedReader(new InputStreamReader(inFun.apply(targets.get(i)), StandardCharsets.ISO_8859_1));while ((c = bufr.read()) != -1) {out.write(c);}out.flush();if (bufr != null) {bufr.close();}}logger.info("成功壓縮{}個(gè)文件,保存地址為【{}】", targets.size(), savePath);} catch (IOException r) {throw new RuntimeException("文件壓縮失敗");} finally {if (bufr != null) {bufr.close();}}}/*** 獲取apache的ZipOutputStream流* @param savePath 保存壓縮文件的路徑* @return* @throws FileNotFoundException 如果保存路徑不存在,那么將會(huì)拋異常*/private static ZipOutputStream getOutPutStream(String savePath) throws FileNotFoundException {//輸出的壓縮原始文件流fileDir + "\\" + "詳情.zip"FileOutputStream f = new FileOutputStream(new File(savePath));// 計(jì)算和校驗(yàn)文件CheckedOutputStream csum = new CheckedOutputStream(f, new CRC32());// 輸出的壓縮文件流ZipOutputStream zos = new ZipOutputStream(csum);zos.setComment("dist文件壓縮流");//設(shè)置壓縮工具右邊的文字編碼 防止右邊的說明文字亂碼zos.setEncoding(System.getProperty("sun.jnu.encoding"));return zos;}/*** 獲取文件名* @param filePath* @return*/public static String getFileName(String filePath) {int idx = StringUtils.lastIndexOf(filePath, File.separator);if (idx != -1) {return StringUtils.substring(filePath, idx + 1);}return filePath;}}轉(zhuǎn)載于:https://www.cnblogs.com/qiaozhuangshi/p/11198157.html
總結(jié)
- 上一篇: python---4
- 下一篇: java之单元测试