package com.test.utils;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 文件相关的工具类
*
* @author kbse
*/
public class PathUtils {
private static Logger logger = LoggerFactory.getLogger(PathUtils.class);
/**
* 删除文件(夹)及其子文件(夹)
*
* @param file 文件
*/
public static void deleteFile(File file) {
if (!file.exists()) {
return;
}
if (file.isFile()) {
file.delete();
} else if (file.isDirectory()) {
try {
FileUtils.deleteDirectory(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 拷贝文件
*
* @param oldPath 文件源路径
* @param newPath 文件目标路径
*/
public static void copyFile(String oldPath, String newPath) {
try {
int byteread = 0;
File oldfile = new File(oldPath);
File newfile = new File(newPath);
//文件存在时
if (oldfile.exists()) {
//读入源文件
InputStream inStream = new FileInputStream(oldfile);
OutputStream fs = new FileOutputStream(newfile);
byte[] buffer = new byte[1000];
while ((byteread = inStream.read(buffer)) != -1) {
fs.write(buffer, 0, byteread);
}
inStream.close();
fs.close();
}
} catch (Exception e) {
logger.error("复制单个文件操作出错");
e.printStackTrace();
}
}
/**
* 将 sourceDirPath 压缩成 zipFilePath 压缩包
*
* @param sourceDirPath 源文件目录 eg: D:/data
* @param zipFilePath 压缩包文件目录 eg: D:/data.zip
* @throws IOException 文件相关异常
*/
public static void pack(String sourceDirPath, String zipFilePath) throws IOException {
Path p = Files.createFile(Paths.get(zipFilePath));
try (ZipOutputStream zs = new ZipOutputStream(Files.newOutputStream(p))) {
Path pp = Paths.get(sourceDirPath);
Files.walk(pp)
.filter(path -> !Files.isDirectory(path))
.forEach(path -> {
ZipEntry zipEntry = new ZipEntry(pp.relativize(path).toString());
try {
zs.putNextEntry(zipEntry);
Files.copy(path, zs);
zs.closeEntry();
} catch (IOException e) {
logger.error("pack file error src: {} msg: ", sourceDirPath, e.getMessage());
}
});
}
}
}
删除文件(夹)及其子文件(夹), 拷贝文件, 压缩文件夹及其下面的所有的子文件
最新推荐文章于 2021-05-04 17:42:07 发布