压缩相关→ZipUtils

本文介绍了一个用于批量压缩和解压文件的Java工具类,提供了压缩文件、批量压缩文件集、解压文件及获取压缩文件内文件路径等功能。
   
  import java.io.BufferedInputStream;
  import java.io.BufferedOutputStream;
  import java.io.File;
  import java.io.FileInputStream;
  import java.io.FileOutputStream;
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.OutputStream;
  import java.util.ArrayList;
  import java.util.Collection;
  import java.util.Enumeration;
  import java.util.List;
  import java.util.zip.ZipEntry;
  import java.util.zip.ZipFile;
  import java.util.zip.ZipOutputStream;
   
  /**
  * <pre>
  * author: Blankj
  * blog : http://blankj.com
  * time : 2016/8/27
  * desc : 压缩相关工具类
  * </pre>
  */
  public final class ZipUtils {
   
  private ZipUtils() {
  throw new UnsupportedOperationException("u can't instantiate me...");
  }
   
  private static final int KB = 1024;
   
  /**
  * 批量压缩文件
  *
  * @param resFiles 待压缩文件集合
  * @param zipFilePath 压缩文件路径
  * @return {@code true}: 压缩成功<br>{@code false}: 压缩失败
  * @throws IOException IO错误时抛出
  */
  public static boolean zipFiles(Collection<File> resFiles, String zipFilePath)
  throws IOException {
  return zipFiles(resFiles, zipFilePath, null);
  }
   
  /**
  * 批量压缩文件
  *
  * @param resFiles 待压缩文件集合
  * @param zipFilePath 压缩文件路径
  * @param comment 压缩文件的注释
  * @return {@code true}: 压缩成功<br>{@code false}: 压缩失败
  * @throws IOException IO错误时抛出
  */
  public static boolean zipFiles(Collection<File> resFiles, String zipFilePath, String comment)
  throws IOException {
  return zipFiles(resFiles, FileUtils.getFileByPath(zipFilePath), comment);
  }
   
  /**
  * 批量压缩文件
  *
  * @param resFiles 待压缩文件集合
  * @param zipFile 压缩文件
  * @return {@code true}: 压缩成功<br>{@code false}: 压缩失败
  * @throws IOException IO错误时抛出
  */
  public static boolean zipFiles(Collection<File> resFiles, File zipFile)
  throws IOException {
  return zipFiles(resFiles, zipFile, null);
  }
   
  /**
  * 批量压缩文件
  *
  * @param resFiles 待压缩文件集合
  * @param zipFile 压缩文件
  * @param comment 压缩文件的注释
  * @return {@code true}: 压缩成功<br>{@code false}: 压缩失败
  * @throws IOException IO错误时抛出
  */
  public static boolean zipFiles(Collection<File> resFiles, File zipFile, String comment)
  throws IOException {
  if (resFiles == null || zipFile == null) return false;
  ZipOutputStream zos = null;
  try {
  zos = new ZipOutputStream(new FileOutputStream(zipFile));
  for (File resFile : resFiles) {
  if (!zipFile(resFile, "", zos, comment)) return false;
  }
  return true;
  } finally {
  if (zos != null) {
  zos.finish();
  CloseUtils.closeIO(zos);
  }
  }
  }
   
  /**
  * 压缩文件
  *
  * @param resFilePath 待压缩文件路径
  * @param zipFilePath 压缩文件路径
  * @return {@code true}: 压缩成功<br>{@code false}: 压缩失败
  * @throws IOException IO错误时抛出
  */
  public static boolean zipFile(String resFilePath, String zipFilePath)
  throws IOException {
  return zipFile(resFilePath, zipFilePath, null);
  }
   
  /**
  * 压缩文件
  *
  * @param resFilePath 待压缩文件路径
  * @param zipFilePath 压缩文件路径
  * @param comment 压缩文件的注释
  * @return {@code true}: 压缩成功<br>{@code false}: 压缩失败
  * @throws IOException IO错误时抛出
  */
  public static boolean zipFile(String resFilePath, String zipFilePath, String comment)
  throws IOException {
  return zipFile(FileUtils.getFileByPath(resFilePath), FileUtils.getFileByPath(zipFilePath), comment);
  }
   
  /**
  * 压缩文件
  *
  * @param resFile 待压缩文件
  * @param zipFile 压缩文件
  * @return {@code true}: 压缩成功<br>{@code false}: 压缩失败
  * @throws IOException IO错误时抛出
  */
  public static boolean zipFile(File resFile, File zipFile)
  throws IOException {
  return zipFile(resFile, zipFile, null);
  }
   
  /**
  * 压缩文件
  *
  * @param resFile 待压缩文件
  * @param zipFile 压缩文件
  * @param comment 压缩文件的注释
  * @return {@code true}: 压缩成功<br>{@code false}: 压缩失败
  * @throws IOException IO错误时抛出
  */
  public static boolean zipFile(File resFile, File zipFile, String comment)
  throws IOException {
  if (resFile == null || zipFile == null) return false;
  ZipOutputStream zos = null;
  try {
  zos = new ZipOutputStream(new FileOutputStream(zipFile));
  return zipFile(resFile, "", zos, comment);
  } finally {
  if (zos != null) {
  CloseUtils.closeIO(zos);
  }
  }
  }
   
  /**
  * 压缩文件
  *
  * @param resFile 待压缩文件
  * @param rootPath 相对于压缩文件的路径
  * @param zos 压缩文件输出流
  * @param comment 压缩文件的注释
  * @return {@code true}: 压缩成功<br>{@code false}: 压缩失败
  * @throws IOException IO错误时抛出
  */
  private static boolean zipFile(File resFile, String rootPath, ZipOutputStream zos, String comment)
  throws IOException {
  rootPath = rootPath + (isSpace(rootPath) ? "" : File.separator) + resFile.getName();
  if (resFile.isDirectory()) {
  File[] fileList = resFile.listFiles();
  // 如果是空文件夹那么创建它,我把'/'换为File.separator测试就不成功,eggPain
  if (fileList == null || fileList.length <= 0) {
  ZipEntry entry = new ZipEntry(rootPath + '/');
  if (!StringUtils.isEmpty(comment)) entry.setComment(comment);
  zos.putNextEntry(entry);
  zos.closeEntry();
  } else {
  for (File file : fileList) {
  // 如果递归返回false则返回false
  if (!zipFile(file, rootPath, zos, comment)) return false;
  }
  }
  } else {
  InputStream is = null;
  try {
  is = new BufferedInputStream(new FileInputStream(resFile));
  ZipEntry entry = new ZipEntry(rootPath);
  if (!StringUtils.isEmpty(comment)) entry.setComment(comment);
  zos.putNextEntry(entry);
  byte buffer[] = new byte[KB];
  int len;
  while ((len = is.read(buffer, 0, KB)) != -1) {
  zos.write(buffer, 0, len);
  }
  zos.closeEntry();
  } finally {
  CloseUtils.closeIO(is);
  }
  }
  return true;
  }
   
  /**
  * 批量解压文件
  *
  * @param zipFiles 压缩文件集合
  * @param destDirPath 目标目录路径
  * @return {@code true}: 解压成功<br>{@code false}: 解压失败
  * @throws IOException IO错误时抛出
  */
  public static boolean unzipFiles(Collection<File> zipFiles, String destDirPath)
  throws IOException {
  return unzipFiles(zipFiles, FileUtils.getFileByPath(destDirPath));
  }
   
  /**
  * 批量解压文件
  *
  * @param zipFiles 压缩文件集合
  * @param destDir 目标目录
  * @return {@code true}: 解压成功<br>{@code false}: 解压失败
  * @throws IOException IO错误时抛出
  */
  public static boolean unzipFiles(Collection<File> zipFiles, File destDir)
  throws IOException {
  if (zipFiles == null || destDir == null) return false;
  for (File zipFile : zipFiles) {
  if (!unzipFile(zipFile, destDir)) return false;
  }
  return true;
  }
   
  /**
  * 解压文件
  *
  * @param zipFilePath 待解压文件路径
  * @param destDirPath 目标目录路径
  * @return {@code true}: 解压成功<br>{@code false}: 解压失败
  * @throws IOException IO错误时抛出
  */
  public static boolean unzipFile(String zipFilePath, String destDirPath)
  throws IOException {
  return unzipFile(FileUtils.getFileByPath(zipFilePath), FileUtils.getFileByPath(destDirPath));
  }
   
  /**
  * 解压文件
  *
  * @param zipFile 待解压文件
  * @param destDir 目标目录
  * @return {@code true}: 解压成功<br>{@code false}: 解压失败
  * @throws IOException IO错误时抛出
  */
  public static boolean unzipFile(File zipFile, File destDir)
  throws IOException {
  return unzipFileByKeyword(zipFile, destDir, null) != null;
  }
   
  /**
  * 解压带有关键字的文件
  *
  * @param zipFilePath 待解压文件路径
  * @param destDirPath 目标目录路径
  * @param keyword 关键字
  * @return 返回带有关键字的文件链表
  * @throws IOException IO错误时抛出
  */
  public static List<File> unzipFileByKeyword(String zipFilePath, String destDirPath, String keyword)
  throws IOException {
  return unzipFileByKeyword(FileUtils.getFileByPath(zipFilePath),
  FileUtils.getFileByPath(destDirPath), keyword);
  }
   
  /**
  * 解压带有关键字的文件
  *
  * @param zipFile 待解压文件
  * @param destDir 目标目录
  * @param keyword 关键字
  * @return 返回带有关键字的文件链表
  * @throws IOException IO错误时抛出
  */
  public static List<File> unzipFileByKeyword(File zipFile, File destDir, String keyword)
  throws IOException {
  if (zipFile == null || destDir == null) return null;
  List<File> files = new ArrayList<>();
  ZipFile zf = new ZipFile(zipFile);
  Enumeration<?> entries = zf.entries();
  while (entries.hasMoreElements()) {
  ZipEntry entry = ((ZipEntry) entries.nextElement());
  String entryName = entry.getName();
  if (StringUtils.isEmpty(keyword) || FileUtils.getFileName(entryName).toLowerCase().contains(keyword.toLowerCase())) {
  String filePath = destDir + File.separator + entryName;
  File file = new File(filePath);
  files.add(file);
  if (entry.isDirectory()) {
  if (!FileUtils.createOrExistsDir(file)) return null;
  } else {
  if (!FileUtils.createOrExistsFile(file)) return null;
  InputStream in = null;
  OutputStream out = null;
  try {
  in = new BufferedInputStream(zf.getInputStream(entry));
  out = new BufferedOutputStream(new FileOutputStream(file));
  byte buffer[] = new byte[KB];
  int len;
  while ((len = in.read(buffer)) != -1) {
  out.write(buffer, 0, len);
  }
  } finally {
  CloseUtils.closeIO(in, out);
  }
  }
  }
  }
  return files;
  }
   
  /**
  * 获取压缩文件中的文件路径链表
  *
  * @param zipFilePath 压缩文件路径
  * @return 压缩文件中的文件路径链表
  * @throws IOException IO错误时抛出
  */
  public static List<String> getFilesPath(String zipFilePath)
  throws IOException {
  return getFilesPath(FileUtils.getFileByPath(zipFilePath));
  }
   
  /**
  * 获取压缩文件中的文件路径链表
  *
  * @param zipFile 压缩文件
  * @return 压缩文件中的文件路径链表
  * @throws IOException IO错误时抛出
  */
  public static List<String> getFilesPath(File zipFile)
  throws IOException {
  if (zipFile == null) return null;
  List<String> paths = new ArrayList<>();
  Enumeration<?> entries = getEntries(zipFile);
  while (entries.hasMoreElements()) {
  paths.add(((ZipEntry) entries.nextElement()).getName());
  }
  return paths;
  }
   
  /**
  * 获取压缩文件中的注释链表
  *
  * @param zipFilePath 压缩文件路径
  * @return 压缩文件中的注释链表
  * @throws IOException IO错误时抛出
  */
  public static List<String> getComments(String zipFilePath)
  throws IOException {
  return getComments(FileUtils.getFileByPath(zipFilePath));
  }
   
  /**
  * 获取压缩文件中的注释链表
  *
  * @param zipFile 压缩文件
  * @return 压缩文件中的注释链表
  * @throws IOException IO错误时抛出
  */
  public static List<String> getComments(File zipFile)
  throws IOException {
  if (zipFile == null) return null;
  List<String> comments = new ArrayList<>();
  Enumeration<?> entries = getEntries(zipFile);
  while (entries.hasMoreElements()) {
  ZipEntry entry = ((ZipEntry) entries.nextElement());
  comments.add(entry.getComment());
  }
  return comments;
  }
   
  /**
  * 获取压缩文件中的文件对象
  *
  * @param zipFilePath 压缩文件路径
  * @return 压缩文件中的文件对象
  * @throws IOException IO错误时抛出
  */
  public static Enumeration<?> getEntries(String zipFilePath)
  throws IOException {
  return getEntries(FileUtils.getFileByPath(zipFilePath));
  }
   
  /**
  * 获取压缩文件中的文件对象
  *
  * @param zipFile 压缩文件
  * @return 压缩文件中的文件对象
  * @throws IOException IO错误时抛出
  */
  public static Enumeration<?> getEntries(File zipFile)
  throws IOException {
  if (zipFile == null) return null;
  return new ZipFile(zipFile).entries();
  }
   
  private static boolean isSpace(String s) {
  if (s == null) return true;
  for (int i = 0, len = s.length(); i < len; ++i) {
  if (!Character.isWhitespace(s.charAt(i))) {
  return false;
  }
  }
  return true;
  }
  }
package com.isa.navi.jni.hmi; import com.isa.navi.utils.LogUtils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.zip.Deflater; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; /** * ZipUtils 类是一个工具类,用于处理 ZIP 文件的压缩和解压缩操作。 * 它采用了单例设计模式,确保整个应用程序中只有一个 ZipUtils 实例。 */ public class ZipUtils { /** * 用于日志记录的标签。 */ static private final String TAG = "UPDATE"; /** * ZipUtils 类的单例实例。 * 使用 volatile 关键字确保多线程环境下的可见性和有序性。 */ private volatile static ZipUtils mInstance; /** * 缓冲区大小 */ private static final int BUFFER_SIZE = 10 * 1024 * 1024; private long lastCheckTime; /** * 私有构造函数,防止外部类通过 `new` 关键字创建 ZipUtils 实例。 */ private ZipUtils() { } /** * 获取 ZipUtils 类的单例实例。 * * @return ZipUtils 类的单例实例。 */ public static ZipUtils getInstance() { if (mInstance == null) { synchronized (ZipUtils.class) { if (mInstance == null) { mInstance = new ZipUtils(); } } } return mInstance; } public boolean unzip(String zipFilePath, String outputDir) { boolean success = true; LogUtils.i("开始解压ZIP文件: " + zipFilePath + " 到目录: " + outputDir); // 创建输出目录(如果不存在) File dir = new File(outputDir); if (!dir.exists()) { LogUtils.d("尝试创建输出目录: " + outputDir); if (!dir.mkdirs()) { LogUtils.e("无法创建输出目录: " + outputDir); return false; } LogUtils.i("成功创建输出目录: " + outputDir); } // 获取输出目录的规范路径用于安全检查 String canonicalOutputDir; try { canonicalOutputDir = dir.getCanonicalPath(); LogUtils.d("输出目录规范路径: " + canonicalOutputDir); } catch (IOException e) { LogUtils.e("获取输出目录规范路径失败: " + e.getMessage()); return false; } try (ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFilePath)))) { LogUtils.d("打开ZIP输入流成功"); ZipEntry entry; int entryCount = 0; while ((entry = zis.getNextEntry()) != null) { entryCount++; String originalEntryName = entry.getName(); LogUtils.d("处理条目 #" + entryCount + ": " + originalEntryName + " | 目录: " + entry.isDirectory() + " | 大小: " + entry.getSize() + " bytes"); // 规范化路径处理 String entryName = normalizePath(originalEntryName); if (entryName.isEmpty()) { LogUtils.e("跳过无效条目: " + originalEntryName); continue; } LogUtils.d("规范化后路径: " + entryName); File outputFile = new File(outputDir, entryName); // 详细路径安全日志 try { String canonicalPath = outputFile.getCanonicalPath(); LogUtils.d("目标文件规范路径: " + canonicalPath); // 路径遍历安全检查 if (!canonicalPath.startsWith(canonicalOutputDir + File.separator)) { LogUtils.e("安全违规: 条目 " + originalEntryName + " 试图逃逸到 " + canonicalPath); success = false; continue; } } catch (IOException e) { LogUtils.e("路径解析错误: " + outputFile.getAbsolutePath() + " | 错误: " + e.getMessage()); success = false; continue; } // 创建父目录(如果需要) File parentDir = outputFile.getParentFile(); if (parentDir != null && !parentDir.exists()) { LogUtils.d("尝试创建父目录: " + parentDir.getAbsolutePath()); if (!parentDir.mkdirs()) { LogUtils.e("无法创建父目录: " + parentDir.getAbsolutePath()); success = false; continue; } LogUtils.i("成功创建父目录: " + parentDir.getAbsolutePath()); } if (!entry.isDirectory()) { LogUtils.d("解压文件到: " + outputFile.getAbsolutePath()); try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outputFile))) { byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead; long totalBytes = 0; while ((bytesRead = zis.read(buffer)) != -1) { bos.write(buffer, 0, bytesRead); totalBytes += bytesRead; // 安全检查逻辑(每秒最多1次) long currentTime = System.currentTimeMillis(); if (currentTime - lastCheckTime > 1000) { synchronized (this) { if (currentTime - lastCheckTime > 1000) { LogUtils.d("执行安全检测..."); if (!HmiJNIImpl.getInstance().mapControl()) { LogUtils.e("安全检测失败,终止解压"); return false; } lastCheckTime = currentTime; } } } } LogUtils.i("成功解压文件: " + outputFile.getName() + " | 大小: " + totalBytes + " bytes"); } catch (IOException e) { LogUtils.e("写入文件失败: " + outputFile.getAbsolutePath() + " | 错误: " + e.getMessage()); success = false; // 删除部分写入的文件 if (outputFile.exists() && !outputFile.delete()) { LogUtils.e("无法删除部分写入的文件: " + outputFile.getAbsolutePath()); } } } else { LogUtils.d("创建目录: " + outputFile.getAbsolutePath()); if (!outputFile.exists()) { if (!outputFile.mkdirs()) { LogUtils.e("无法创建目录: " + outputFile.getAbsolutePath()); success = false; } else { LogUtils.i("成功创建目录: " + outputFile.getAbsolutePath()); } } else { LogUtils.d("目录已存在: " + outputFile.getAbsolutePath()); } } zis.closeEntry(); LogUtils.d("完成处理条目: " + originalEntryName); } LogUtils.i("处理完成所有条目,共 " + entryCount + " 个"); } catch (IOException e) { LogUtils.e("解压ZIP文件时发生错误: " + e.getMessage()); success = false; } // 结果处理 if (success) { LogUtils.i("解压成功,尝试删除原始ZIP文件: " + zipFilePath); File zipFile = new File(zipFilePath); if (zipFile.delete()) { LogUtils.i("成功删除原始ZIP文件: " + zipFilePath); } else { LogUtils.e("无法删除原始ZIP文件: " + zipFilePath); success = false; } } else { LogUtils.e("解压过程中遇到错误,保留原始ZIP文件"); } LogUtils.i("解压结果: " + (success ? "成功" : "失败")); return success; } // 增强的路径规范化方法 private String normalizePath(String path) { if (path == null || path.trim().isEmpty()) { LogUtils.e("收到空路径"); return ""; } LogUtils.d("原始路径: " + path); // 统一路径分隔符并压缩连续分隔符 String normalized = path.replace('\\', '/') .replaceAll("/+", "/") // 合并所有连续斜杠 .trim(); // 移除开头斜杠 if (normalized.startsWith("/")) { normalized = normalized.substring(1); LogUtils.d("移除开头斜杠: " + normalized); } // 处理Windows盘符路径 if (normalized.matches("[a-zA-Z]:[/\\\\].*")) { LogUtils.e("检测到绝对路径: " + path); return ""; } // 处理路径遍历攻击 if (normalized.contains("..")) { // 精确检测路径遍历序列 if (normalized.contains("../") || normalized.contains("/..") || normalized.startsWith("..") || normalized.endsWith("..")) { LogUtils.e("检测到路径遍历攻击: " + path); return ""; } } LogUtils.d("规范化后路径: " + normalized); return normalized; } /** * 压缩文件或目录到ZIP文件 * * @param sourcePath 要压缩的文件或目录路径 * @param outputZipPath 输出的ZIP文件路径 * @param includeParent 是否包含父目录 * @return 压缩是否成功 */ public boolean zip(String sourcePath, String outputZipPath, boolean includeParent) { LogUtils.i(TAG, "sourcePath:" + sourcePath); LogUtils.i(TAG, "outputZipPath:" + outputZipPath); File sourceFile = new File(sourcePath); if (!sourceFile.exists()) { LogUtils.e(TAG, "源文件/目录不存在: " + sourcePath); return false; } try (FileOutputStream fos = new FileOutputStream(outputZipPath); BufferedOutputStream bos = new BufferedOutputStream(fos); ZipOutputStream zos = new ZipOutputStream(bos)) { // 设置压缩级别(可选) zos.setLevel(Deflater.BEST_SPEED); if (sourceFile.isDirectory()) { // 压缩目录 if(!zipDirectory(sourceFile, sourceFile.getParentFile(), zos, includeParent)) { return false; } } else { // 压缩单个文件 if(!zipFile(sourceFile, sourceFile.getParentFile(), zos, includeParent)) { return false; } } LogUtils.i(TAG, "压缩完成: " + outputZipPath); return true; } catch (IOException e) { LogUtils.e(TAG, "压缩过程中发生错误: " + e.getMessage()); return false; } } /** * 递归压缩目录 * * @param directory 要压缩的目录 * @param baseDir 基础目录(用于计算相对路径) * @param zos Zip输出流 * @param includeParent 是否包含父目录 * @throws IOException IO异常 */ private boolean zipDirectory(File directory, File baseDir, ZipOutputStream zos, boolean includeParent) throws IOException { // 获取目录中的所有文件和子目录 File[] files = directory.listFiles(); if (files == null) return false; // 如果目录不为空,添加目录条目(空目录也需要添加) if (files.length > 0 || includeParent) { String entryName = getRelativePath(directory, baseDir, includeParent) + "/"; ZipEntry dirEntry = new ZipEntry(entryName); dirEntry.setTime(directory.lastModified()); zos.putNextEntry(dirEntry); zos.closeEntry(); } // 递归处理所有文件和子目录 for (File file : files) { if (file.isDirectory()) { if(!zipDirectory(file, baseDir, zos, includeParent)) { return false; } } else { if(!zipFile(file, baseDir, zos, includeParent)) { return false; } } } return true; } /** * 压缩单个文件 * * @param file 要压缩的文件 * @param baseDir 基础目录(用于计算相对路径) * @param zos Zip输出流 * @param includeParent 是否包含父目录 * @throws IOException IO异常 */ private boolean zipFile(File file, File baseDir, ZipOutputStream zos, boolean includeParent) throws IOException { // 创建ZIP条目 String entryName = getRelativePath(file, baseDir, includeParent); ZipEntry zipEntry = new ZipEntry(entryName); zipEntry.setTime(file.lastModified()); zipEntry.setSize(file.length()); zos.putNextEntry(zipEntry); // 写入文件内容 try (FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis)) { byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead; while ((bytesRead = bis.read(buffer)) != -1) { zos.write(buffer, 0, bytesRead); // 优化后的检查逻辑(每秒最多1次) long currentTime = System.currentTimeMillis(); if (currentTime - lastCheckTime > 1000) { synchronized (this) { if (currentTime - lastCheckTime > 1000) { if (!HmiJNIImpl.getInstance().mapControl()) { return false; } lastCheckTime = currentTime; } } } } } zos.closeEntry(); return true; } /** * 获取文件相对于基础目录的路径 * * @param file 文件或目录 * @param baseDir 基础目录 * @param includeParent 是否包含父目录 * @return 相对路径 */ private String getRelativePath(File file, File baseDir, boolean includeParent) { Path filePath = file.toPath(); Path basePath = baseDir.toPath(); if (includeParent) { // 包含父目录(压缩整个目录结构) return basePath.relativize(filePath).toString().replace(File.separator, "/"); } else { // 不包含父目录(只压缩内容) Path parentPath = file.getParentFile().toPath(); return parentPath.relativize(filePath).toString().replace(File.separator, "/"); } } public String[] findEncryptedZipFiles(String directory) { File dir = new File(directory); String[] result = new String[2];; if (!dir.exists() || !dir.isDirectory()) { System.err.println("指定目录不存在或不是一个目录: " + directory); return result; } File[] files = dir.listFiles(); if (files == null || files.length == 0) { System.err.println("目录为空: " + directory); return result; } for (File file : files) { String fileName = file.getName(); if (fileName.endsWith(".zip.enc.sig")) { result[0] = file.getAbsolutePath(); continue; } if (fileName.endsWith(".zip.enc")) { result[1] = file.getAbsolutePath(); } } return result; } /** * 压缩指定目录下的所有DB文件到ZIP包 * * @param sourceDir 源目录路径 * @param outputZipPath 输出的ZIP文件路径 * @return 压缩是否成功 */ public boolean zipDbFiles(String sourceDir, String outputZipPath) { File dir = new File(sourceDir); if (!dir.exists() || !dir.isDirectory()) { LogUtils.e(TAG, "源目录不存在或不是目录: " + sourceDir); return false; } // 查找所有.db文件 List<File> dbFiles = findFilesByExtension(dir, ".db"); if (dbFiles.isEmpty()) { LogUtils.e(TAG, "未找到任何.db文件: " + sourceDir); return false; } // 压缩文件 return zipFileList(dbFiles, dir, outputZipPath, false); } /** * 压缩指定目录下的特定扩展名文件到ZIP包 * * @param sourceDir 源目录路径 * @param outputZipPath 输出的ZIP文件路径 * @param extension 文件扩展名(如".db", ".txt") * @return 压缩是否成功 */ public boolean zipFilesByExtension(String sourceDir, String outputZipPath, String extension) { File dir = new File(sourceDir); if (!dir.exists() || !dir.isDirectory()) { LogUtils.e(TAG, "源目录不存在或不是目录: " + sourceDir); return false; } // 查找指定扩展名的文件 List<File> files = findFilesByExtension(dir, extension); if (files.isEmpty()) { LogUtils.e(TAG, "未找到任何" + extension + "文件: " + sourceDir); return false; } return zipFileList(files, dir, outputZipPath, false); } /** * 压缩文件列表到ZIP包 * * @param files 要压缩的文件列表 * @param baseDir 基础目录(用于计算相对路径) * @param outputZipPath 输出的ZIP文件路径 * @param preservePath 是否保留目录结构 * @return 压缩是否成功 */ public boolean zipFileList(List<File> files, File baseDir, String outputZipPath, boolean preservePath) { if (files == null || files.isEmpty()) { LogUtils.e(TAG, "文件列表为空"); return false; } try (FileOutputStream fos = new FileOutputStream(outputZipPath); BufferedOutputStream bos = new BufferedOutputStream(fos); ZipOutputStream zos = new ZipOutputStream(bos)) { zos.setLevel(Deflater.BEST_SPEED); // 设置压缩级别 for (File file : files) { if (!file.exists() || file.isDirectory()) { LogUtils.d(TAG, "跳过不存在的文件或目录: " + file.getAbsolutePath()); continue; } // 计算ZIP条目名称 String entryName = preservePath ? getRelativePath(file, baseDir) : file.getName(); // 添加文件到ZIP if(!addFileToZip(file, entryName, zos)) { return false; } } LogUtils.i(TAG, "成功压缩 " + files.size() + " 个文件到: " + outputZipPath); return true; } catch (IOException e) { LogUtils.e(TAG, "压缩文件列表时出错: " + e.getMessage()); return false; } } /** * 查找指定目录下特定扩展名的所有文件 * * @param directory 要搜索的目录 * @param extension 文件扩展名(如".db") * @return 匹配的文件列表 */ private List<File> findFilesByExtension(File directory, String extension) { List<File> result = new ArrayList<>(); if (directory == null || !directory.isDirectory()) { return result; } File[] files = directory.listFiles(); if (files == null) { return result; } // 确保扩展名以点开头 String normalizedExtension = extension.startsWith(".") ? extension.toLowerCase() : "." + extension.toLowerCase(); for (File file : files) { if (file.isFile() && file.getName().toLowerCase().endsWith(normalizedExtension)) { result.add(file); } } return result; } /** * 添加单个文件到ZIP输出流 * * @param file 要添加的文件 * @param entryName ZIP条目名称 * @param zos ZIP输出流 */ private boolean addFileToZip(File file, String entryName, ZipOutputStream zos) throws IOException { ZipEntry zipEntry = new ZipEntry(entryName); zipEntry.setTime(file.lastModified()); zipEntry.setSize(file.length()); zos.putNextEntry(zipEntry); try (FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis)) { byte[] buffer = new byte[1024 * 1024]; int bytesRead; while ((bytesRead = bis.read(buffer)) != -1) { zos.write(buffer, 0, bytesRead); // 优化后的检查逻辑(每秒最多1次) long currentTime = System.currentTimeMillis(); if (currentTime - lastCheckTime > 1000) { synchronized (this) { if (currentTime - lastCheckTime > 1000) { if (!HmiJNIImpl.getInstance().mapControl()) { return false; } lastCheckTime = currentTime; } } } } } zos.closeEntry(); LogUtils.d(TAG, "添加文件到ZIP: " + entryName); return true; } /** * 获取文件相对于基础目录的路径 * * @param file 文件 * @param baseDir 基础目录 * @return 相对路径 */ private String getRelativePath(File file, File baseDir) { Path filePath = file.toPath(); Path basePath = baseDir.toPath(); return basePath.relativize(filePath).toString().replace(File.separator, "/"); } } unzip 输入哪些?
最新发布
07-29
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值