如果文件1.txt已存在 则生产1(1).txt 1(1).txt已存在 则生成1(2).txt 。。。。直到不存在为止
strutil为hutool工具类
代码语言:javascript复制 /**
* 如果文件已存在 则自动重命名为带后缀的文件名
*/
private String generateNotExistFileName(String src) {
String path = src;
String extension = FilenameUtils.getExtension(path);
boolean hasExtension = StrUtil.isNotBlank(extension);
int i = 1;
while (FileUtil.exist(path)) {
if (hasExtension) {
path = StrUtil.subBefore(path, ".", true);
}
boolean hasSuffix = path.contains("(") && path.endsWith(")");
if (!hasSuffix) {
path = path "(" i ")";
i ;
} else {
String suffix = StrUtil.subAfter(path, "(", true);
path = StrUtil.subBefore(path, "(", true);
final char c = suffix.charAt(0);
final int integer = Convert.toInt(c) 1;
path = path "(" integer ")";
}
path = path "." extension;
}
return path;
}