java 文件压缩/解压工具类
·
一个常用的文件压缩工具类, 包括rar文件也可以使用unZip解压
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import org.apache.commons.lang3.ObjectUtils;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FileUtil{
private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
public static String copyTo(String sourceFile, String targetPath) {
if (ObjectUtils.isEmpty(sourceFile)) {
return "";
}
try {
Path sourceFilePath = Paths.get(sourceFile);
return copyTo(sourceFile, targetPath, sourceFilePath.getFileName().toString());
} catch (Exception e) {
logger.error("复制文件失败", e);
}
return "";
}
public static String copyTo(String sourceFile, String targetPath, String newFileName) {
if (ObjectUtils.isEmpty(sourceFile)) {
return "";
}
try {
Path sourceFilePath = Paths.get(sourceFile);
Path targetDir = Paths.get(targetPath);
if (!StringUtils.contains(newFileName, ".")) {
newFileName = newFileName + getFileExtension(sourceFilePath);
}
Path targetFile = targetDir.resolve(newFileName);
// 确保目标目录存在
Files.createDirectories(targetDir);
// 复制文件(覆盖已存在文件)
Files.copy(sourceFilePath, targetFile, StandardCopyOption.REPLACE_EXISTING);
return targetPath + newFileName;
// return StringUtils.replace(targetPath + newFileName, RuoYiConfig.getProfile(), "/profile");
} catch (IOException e) {
logger.error("复制文件失败", e);
}
return "";
}
private static String getFileExtension(Path file) {
String fileName = file.getFileName().toString();
int dotIndex = fileName.lastIndexOf('.');
return (dotIndex == -1) ? "" : fileName.substring(dotIndex);
}
public static File zipFiles(List<File> files, String outPath) {
if (!StringUtils.endsWith(outPath, ".zip")) {
outPath += ".zip";
}
File zipFile = FileUtil.file(outPath);
try (ZipOutputStream zipOutputStream = new ZipOutputStream(FileUtil.getOutputStream(zipFile))) {
for (File file : files) {
// 使用 InputStream 将文件写入到 ZIP 文件中的指定路径
try (InputStream in = FileUtil.getInputStream(file)) {
ZipEntry zipEntry = new ZipEntry(file.getName());
zipOutputStream.putNextEntry(zipEntry);
IoUtil.copy(in, zipOutputStream);
zipOutputStream.closeEntry();
}
}
} catch (Exception e) {
logger.error("打包文件失败", e);
}
return zipFile;
}
// Java 原生 ZIP 压缩示例
public static void zipFilePath(List<String> sources, String output) {
if (ObjectUtils.isEmpty(sources)) {
return;
}
try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(Paths.get(output)))) {
for (String eachFile : sources) {
Path source = Paths.get(eachFile);
if (Files.isDirectory(source)) {
Files.walk(source).forEach(path -> {
if (!Files.isDirectory(path)) {
addToZip(zos, path, source.relativize(path).toString());
}
});
} else {
addToZip(zos, source, source.getFileName().toString());
}
}
} catch (IOException e) {
logger.error("压缩文件失败", e);
}
}
private static void addToZip(ZipOutputStream zos, Path file, String entryName) {
try {
zos.putNextEntry(new ZipEntry(entryName));
Files.copy(file, zos);
zos.closeEntry();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static void zipFolder(String source, String target) {
if (ObjectUtils.isEmpty(sourceFile)) {
return;
}
// 确保输出目录存在
Path sourceDir = Paths.get(source);
Path zipFile = Paths.get(target);
try(ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(zipFile))){
Files.createDirectories(zipFile.getParent());
// 使用Files.walk递归遍历所有文件
Files.walk(sourceDir)
.filter(path -> !Files.isDirectory(path))
.forEach(path -> {
try {
// 计算相对路径
String relativePath = sourceDir.relativize(path).toString();
// 处理Windows路径分隔符问题
if (File.separator.equals("\\")) {
relativePath = relativePath.replace("\\", "/");
}
// 创建ZIP条目
ZipEntry zipEntry = new ZipEntry(relativePath);
zos.putNextEntry(zipEntry);
// 复制文件内容
Files.copy(path, zos);
// 关闭当前条目
zos.closeEntry();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
} catch (IOException e) {
logger.error("压缩文件夹失败", e);
}
}
public static void unZip(String zipFilePath, String outputDir) {
if (ObjectUtils.isEmpty(zipFilePath)) {
return;
}
// 确保输出目录存在
File dir = new File(outputDir);
if (!dir.exists()) dir.mkdirs();
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath))) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
File file = new File(outputDir, entry.getName());
// 防止路径穿越攻击(Path Traversal)
if (!file.getCanonicalPath().startsWith(dir.getCanonicalPath() + File.separator)) {
throw new IOException("非法路径: " + entry.getName());
}
// 如果是目录,则创建目录
if (entry.isDirectory()) {
file.mkdirs();
} else {
// 确保父目录存在
file.getParentFile().mkdirs();
// 解压文件
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {
byte[] buffer = new byte[1024];
int len;
while ((len = zis.read(buffer)) > 0) {
bos.write(buffer, 0, len);
}
}
}
zis.closeEntry();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void mkdir(String dir) {
FileUtil.mkdir(dir);
}
}
更多推荐


所有评论(0)