|
@@ -604,4 +604,55 @@ public class FileUtils {
|
|
|
String path = sys_file_net_url + fileUrl.replaceAll("//", "/").replaceAll(file_path2, "");
|
|
|
return path;
|
|
|
}
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 获取本地文件,若不存在则从URL下载
|
|
|
+ */
|
|
|
+ public static Path getOrDownloadFile(String localPath) throws IOException {
|
|
|
+ Path path = Paths.get(localPath);
|
|
|
+
|
|
|
+ // 如果本地文件不存在,则从URL下载
|
|
|
+ if (!Files.exists(path)) {
|
|
|
+ System.out.println("本地文件不存在,开始下载...");
|
|
|
+ // 确保父目录存在
|
|
|
+ Path parentDir = path.getParent();
|
|
|
+ if (parentDir != null && !Files.exists(parentDir)) {
|
|
|
+ Files.createDirectories(parentDir);
|
|
|
+ }
|
|
|
+
|
|
|
+ // 从URL下载文件
|
|
|
+ try (InputStream in = CommonUtil.getOSSInputStream(getNetUrl(localPath))) {
|
|
|
+ Files.copy(in, path);
|
|
|
+ System.out.println("文件下载成功: " + path);
|
|
|
+ } catch (IOException e) {
|
|
|
+ throw new IOException("下载文件失败: " + e.getMessage(), e);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return path;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 生成带后缀的副本路径
|
|
|
+ */
|
|
|
+ public static Path generateCopyPath(Path originalPath, Long pKeyId) {
|
|
|
+ String suffix = "_" + pKeyId + "_copy";
|
|
|
+ String fileName = originalPath.getFileName().toString();
|
|
|
+ int dotIndex = fileName.lastIndexOf('.');
|
|
|
+
|
|
|
+ // 处理带扩展名和不带扩展名的文件
|
|
|
+ String newName = (dotIndex > 0)
|
|
|
+ ? fileName.substring(0, dotIndex) + suffix + fileName.substring(dotIndex)
|
|
|
+ : fileName + suffix;
|
|
|
+
|
|
|
+ return originalPath.resolveSibling(newName);
|
|
|
+ }
|
|
|
+
|
|
|
+ public static void removeFile(String localFilePath) {
|
|
|
+ try {
|
|
|
+ java.nio.file.Files.deleteIfExists(java.nio.file.Paths.get(localFilePath));
|
|
|
+ } catch (Exception e) {
|
|
|
+ // 记录日志但不中断主流程
|
|
|
+ System.err.println("删除本地文件失败: " + localFilePath + ", 错误: " + e.getMessage());
|
|
|
+ }
|
|
|
+ }
|
|
|
}
|