파일을 복사할때 동일한 파일이 존재하는 경우 덮어쓰지 않도록 하려면 이름에 숫자를 붙여서 만들어야 하는 경우가 종종 발생함
fileName.txt, fileName(1).txt, fileName(2).txt ... 와 같이 (숫자)를 붙여서 새로운 파일명을 생성하여 처리
public static String getNewFileName(String toFilePath) {
String dest = toFilePath;
String dot = ".";
if (StringUtils.isEmpty(toFilePath))
return dest;
if(!Files.exists(Paths.get(dest)))
return dest;
try {
File f = new File(toFilePath);
String fileHead = f.getName();
String fileExt = "";
int pos = f.getName().lastIndexOf(dot);
if(pos > -1) {
fileHead = f.getName().substring(0, f.getName().lastIndexOf("."));
fileExt = f.getName().substring(f.getName().lastIndexOf(".")+1);
} else {
dot = "";
}
for (int i = 1; i < Integer.MAX_VALUE; i++) {
dest = Paths.get(f.getParent(), String.format("%s(%d)%s%s", fileHead, i, dot, fileExt)).toString();
if (!Files.exists(Paths.get(dest)))
break;
}
} catch(IllegalStateException ie ) {}
return dest;
}
public static void main(String[] args) throws IOException {
String srcPath = "C:\\Temp\\src.txt";
String destPath = "C:\\Temp\\dest.txt";
destPath = getNewFileName(destPath);
FileUtils.copyFile(new File(srcPath), new File(destPath));
System.out.println(destPath);
}
실행하면 아래 그림처럼 새로운 이름의 파일로 생성 확인
'즐겁게 > anything' 카테고리의 다른 글
ExpiringMap(net.jodah) 지정한 시간 동안만 저장되고 자동 삭제 (0) | 2022.11.02 |
---|---|
JAVA 메모리 사용량 확인 (0) | 2022.10.27 |
JavaMail API를 이용한 메일 발송 (0) | 2022.10.23 |