76 lines
2.5 KiB
Java
76 lines
2.5 KiB
Java
package com.knowledge.base.infrastructure.util;
|
||
|
||
import lombok.extern.slf4j.Slf4j;
|
||
|
||
import java.io.IOException;
|
||
import java.nio.file.*;
|
||
import java.util.List;
|
||
|
||
|
||
/**
|
||
* @author Luke.ye
|
||
* @date 2025/6/20 10:45
|
||
*/
|
||
@Slf4j
|
||
public class LocalFileUtil {
|
||
|
||
/**
|
||
* 批量删除文件(根据 basePath + 相对路径 拼接)
|
||
*
|
||
* @param localPathPrefix 本地搜索路径前缀
|
||
* @param relativePaths 文件相对路径列表
|
||
* @return 删除成功数量
|
||
*/
|
||
public static int deleteFilesByRelativePath(String localPathPrefix, List<String> relativePaths) {
|
||
if (relativePaths == null || relativePaths.isEmpty()) {
|
||
log.info("无需删除文件,相对路径为空");
|
||
return 0;
|
||
}
|
||
|
||
int successCount = 0;
|
||
|
||
for (String relativePath : relativePaths) {
|
||
Path path = Paths.get(localPathPrefix, relativePath).toAbsolutePath().normalize();
|
||
try {
|
||
if (Files.exists(path) && Files.isRegularFile(path)) {
|
||
Files.delete(path);
|
||
log.info("已删除本地文件: {}", path);
|
||
successCount++;
|
||
} else {
|
||
log.warn("文件不存在或不是常规文件,跳过: {}", path);
|
||
}
|
||
} catch (IOException e) {
|
||
log.error("删除本地文件失败: {}", path, e);
|
||
}
|
||
}
|
||
|
||
log.info("批量删除本地文件完成,共 {} 个请求,成功删除 {} 个", relativePaths.size(), successCount);
|
||
return successCount;
|
||
}
|
||
|
||
/**
|
||
* 写入文件到指定目录下(自动创建目录)
|
||
*
|
||
* @param localPathPrefix 本地存储根路径(如 /data/searchable/yyyy-MM-dd)
|
||
* @param relativeDir 目标子目录路径(如 "a/b")
|
||
* @param filename 文件名(如 "xx.pdf")
|
||
* @param content 文件内容字节
|
||
* @return 最终写入的绝对路径
|
||
* @throws IOException 写入失败时抛出
|
||
*/
|
||
public static Path writeFile(String localPathPrefix, String relativeDir, String filename, byte[] content) throws IOException {
|
||
Path dirPath = Paths.get(localPathPrefix, relativeDir).toAbsolutePath().normalize();
|
||
if (!Files.exists(dirPath)) {
|
||
Files.createDirectories(dirPath);
|
||
log.info("创建本地目录: {}", dirPath);
|
||
}
|
||
|
||
Path targetFilePath = dirPath.resolve(filename);
|
||
Files.write(targetFilePath, content);
|
||
log.info("写入本地文件成功: {}", targetFilePath);
|
||
|
||
return targetFilePath;
|
||
}
|
||
}
|
||
|