|
| 1 | +/* |
| 2 | + * Copyright (c) 2022-present Charles7c Authors. All Rights Reserved. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package top.continew.admin.system.util; |
| 18 | + |
| 19 | +import java.util.List; |
| 20 | + |
| 21 | +import lombok.extern.slf4j.Slf4j; |
| 22 | + |
| 23 | +import cn.hutool.core.util.StrUtil; |
| 24 | + |
| 25 | +import top.continew.admin.system.enums.FileTypeEnum; |
| 26 | +import top.continew.admin.system.mapper.FileMapper; |
| 27 | +import top.continew.admin.system.model.entity.FileDO; |
| 28 | +import top.continew.starter.core.util.CollUtils; |
| 29 | + |
| 30 | +/** |
| 31 | + * 文件名生成工具类 |
| 32 | + * |
| 33 | + * <p> |
| 34 | + * 提供文件重名检测和自动重命名功能。当文件名冲突时,自动添加序号后缀,如:file.txt → file(1).txt |
| 35 | + * </p> |
| 36 | + * |
| 37 | + * @author fjwupeng |
| 38 | + * @since 2026/2/06 |
| 39 | + */ |
| 40 | +@Slf4j |
| 41 | +public class FileNameGenerator { |
| 42 | + |
| 43 | + private FileNameGenerator() { |
| 44 | + // 工具类禁止实例化 |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * 生成唯一文件名 |
| 49 | + * |
| 50 | + * <p> |
| 51 | + * 当目标目录存在同名文件时,自动添加序号后缀: |
| 52 | + * <ul> |
| 53 | + * <li>file.txt → file(1).txt → file(2).txt → ...</li> |
| 54 | + * <li>无扩展名:README → README(1) → README(2) → ...</li> |
| 55 | + * <li>隐藏文件:.gitignore → .gitignore(1) → .gitignore(2) → ...</li> |
| 56 | + * </ul> |
| 57 | + * </p> |
| 58 | + * |
| 59 | + * @param fileName 原始文件名 |
| 60 | + * @param parentPath 上级目录路径 |
| 61 | + * @param storageId 存储ID |
| 62 | + * @param fileMapper 文件Mapper |
| 63 | + * @return 唯一文件名 |
| 64 | + */ |
| 65 | + public static String generateUniqueName(String fileName, String parentPath, Long storageId, FileMapper fileMapper) { |
| 66 | + // 1. 先检查原始文件名是否可用 |
| 67 | + boolean exists = existsByName(parentPath, storageId, fileName, fileMapper); |
| 68 | + if (!exists) { |
| 69 | + return fileName; |
| 70 | + } |
| 71 | + |
| 72 | + // 2. 解析文件名 |
| 73 | + String[] parts = parseFileName(fileName); |
| 74 | + String baseName = parts[0]; |
| 75 | + String extension = parts[1]; |
| 76 | + |
| 77 | + // 3. 获取该目录下所有可能的冲突文件名(优化:批量查询) |
| 78 | + List<String> existingNames = selectNamesByParentPath(parentPath, storageId, baseName, fileMapper); |
| 79 | + |
| 80 | + // 4. 寻找第一个可用的序号 |
| 81 | + int counter = 1; |
| 82 | + while (true) { |
| 83 | + String newName = buildFileNameWithCounter(baseName, extension, counter); |
| 84 | + if (!existingNames.contains(newName)) { |
| 85 | + log.debug("文件名 [{}] 重命名为 [{}]", fileName, newName); |
| 86 | + return newName; |
| 87 | + } |
| 88 | + counter++; |
| 89 | + |
| 90 | + // 安全限制,防止无限循环 |
| 91 | + if (counter > 9999) { |
| 92 | + log.warn("文件名重命名超过最大限制,使用当前时间戳: {}", fileName); |
| 93 | + return baseName + "_" + System.currentTimeMillis() + (StrUtil.isNotBlank(extension) ? "." + extension : ""); |
| 94 | + } |
| 95 | + } |
| 96 | + } |
| 97 | + |
| 98 | + /** |
| 99 | + * 解析文件名为基础名和扩展名 |
| 100 | + * |
| 101 | + * <p> |
| 102 | + * 示例: |
| 103 | + * </p> |
| 104 | + * <ul> |
| 105 | + * <li>"document.pdf" → ["document", "pdf"]</li> |
| 106 | + * <li>"README" → ["README", ""]</li> |
| 107 | + * <li>".gitignore" → [".gitignore", ""]</li> |
| 108 | + * <li>"archive.tar.gz" → ["archive.tar", "gz"]</li> |
| 109 | + * </ul> |
| 110 | + * |
| 111 | + * @param fileName 文件名 |
| 112 | + * @return 数组 [基础名, 扩展名],扩展名可能为空字符串 |
| 113 | + */ |
| 114 | + public static String[] parseFileName(String fileName) { |
| 115 | + if (StrUtil.isBlank(fileName)) { |
| 116 | + return new String[]{"", ""}; |
| 117 | + } |
| 118 | + |
| 119 | + // 处理隐藏文件(以.开头) |
| 120 | + boolean isHidden = fileName.startsWith("."); |
| 121 | + String nameWithoutDot = isHidden ? fileName.substring(1) : fileName; |
| 122 | + |
| 123 | + // 处理空文件名(如只有"."的情况) |
| 124 | + if (nameWithoutDot.isEmpty()) { |
| 125 | + return new String[]{fileName, ""}; |
| 126 | + } |
| 127 | + |
| 128 | + // 查找最后一个点号位置 |
| 129 | + int lastDotIndex = nameWithoutDot.lastIndexOf('.'); |
| 130 | + |
| 131 | + // 点号不存在或在开头(如 ".bashrc"),视为无扩展名 |
| 132 | + if (lastDotIndex <= 0) { |
| 133 | + return new String[]{fileName, ""}; |
| 134 | + } |
| 135 | + |
| 136 | + String baseName = isHidden ? "." + nameWithoutDot.substring(0, lastDotIndex) : nameWithoutDot.substring(0, lastDotIndex); |
| 137 | + String extension = nameWithoutDot.substring(lastDotIndex + 1); |
| 138 | + |
| 139 | + // 扩展名不应包含路径分隔符(安全检查) |
| 140 | + if (extension.contains("/") || extension.contains("\\")) { |
| 141 | + return new String[]{fileName, ""}; |
| 142 | + } |
| 143 | + |
| 144 | + return new String[]{baseName, extension}; |
| 145 | + } |
| 146 | + |
| 147 | + /** |
| 148 | + * 构建带序号的文件名 |
| 149 | + * |
| 150 | + * @param baseName 基础名 |
| 151 | + * @param extension 扩展名(可能为空) |
| 152 | + * @param counter 序号(必须 >= 1) |
| 153 | + * @return 新文件名,如 "file(1).txt" |
| 154 | + */ |
| 155 | + public static String buildFileNameWithCounter(String baseName, String extension, int counter) { |
| 156 | + if (counter < 1) { |
| 157 | + throw new IllegalArgumentException("序号必须大于等于1"); |
| 158 | + } |
| 159 | + |
| 160 | + StringBuilder sb = new StringBuilder(baseName); |
| 161 | + sb.append("(").append(counter).append(")"); |
| 162 | + |
| 163 | + if (StrUtil.isNotBlank(extension)) { |
| 164 | + sb.append(".").append(extension); |
| 165 | + } |
| 166 | + |
| 167 | + return sb.toString(); |
| 168 | + } |
| 169 | + |
| 170 | + /** |
| 171 | + * 检查文件是否存在 |
| 172 | + * |
| 173 | + * @param parentPath 上级目录 |
| 174 | + * @param storageId 存储ID |
| 175 | + * @param name 文件名 |
| 176 | + * @param fileMapper 文件Mapper |
| 177 | + * @return true: 存在 |
| 178 | + */ |
| 179 | + private static boolean existsByName(String parentPath, Long storageId, String name, FileMapper fileMapper) { |
| 180 | + return fileMapper.lambdaQuery() |
| 181 | + .eq(FileDO::getParentPath, parentPath) |
| 182 | + .eq(FileDO::getStorageId, storageId) |
| 183 | + .eq(FileDO::getName, name) |
| 184 | + .ne(FileDO::getType, FileTypeEnum.DIR) |
| 185 | + .exists(); |
| 186 | + } |
| 187 | + |
| 188 | + /** |
| 189 | + * 查询指定目录下的文件名称列表(用于重名检测) |
| 190 | + * |
| 191 | + * @param parentPath 上级目录 |
| 192 | + * @param storageId 存储ID |
| 193 | + * @param namePrefix 名称前缀(可为null,表示查询所有) |
| 194 | + * @param fileMapper 文件Mapper |
| 195 | + * @return 文件名列表 |
| 196 | + */ |
| 197 | + private static List<String> selectNamesByParentPath(String parentPath, Long storageId, String namePrefix, FileMapper fileMapper) { |
| 198 | + var wrapper = fileMapper.lambdaQuery() |
| 199 | + .eq(FileDO::getParentPath, parentPath) |
| 200 | + .eq(FileDO::getStorageId, storageId) |
| 201 | + .ne(FileDO::getType, FileTypeEnum.DIR) |
| 202 | + .select(FileDO::getName) |
| 203 | + .last("LIMIT 10000"); // 限制最大查询数量,防止内存溢出 |
| 204 | + |
| 205 | + if (StrUtil.isNotBlank(namePrefix)) { |
| 206 | + wrapper.likeRight(FileDO::getName, namePrefix); |
| 207 | + } |
| 208 | + |
| 209 | + return CollUtils.mapToList(wrapper.list(), FileDO::getName); |
| 210 | + } |
| 211 | +} |
0 commit comments