즐겁게/anything

파일명이 중복일때 숫자를 붙여서 새로운 파일명 만들기

파이브빈즈 2022. 12. 16. 16:52

파일을 복사할때 동일한 파일이 존재하는 경우 덮어쓰지 않도록 하려면 이름에 숫자를 붙여서 만들어야 하는 경우가 종종 발생함

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);
}

 

실행하면 아래 그림처럼 새로운 이름의 파일로 생성 확인

새 파일명으로 생성