package sgis.com.vo; import java.io.File; import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 파일 처리 구현 클래스 * @author */ public class FileUtil { /** 로그처리 객체 */ private static final Logger logger = LoggerFactory.getLogger(FileUtil.class); /** * 파일 이름이 디렉토리에 이미 존재하는지 체크한다 * @param realPath 업로드디렉토리 * @param fileName 업로드파일이름 * @return String 파일이름 */ public static String getUniqueFileName(String realPath, String fileName) { int idx = 0; int cnt = 1; String temp = getSavedFileName(fileName); // 저장할 파일명 생성 File tempFile = new File(realPath+temp); // 기존에 동일한 파일명의 파일 존재하는지 체크 //이미존재하는 파일인지 확인 while(tempFile.exists()) { //기존에 존재하면 확장자랑 파일명을 분리해서 [숫자]를 붙여서 파일이름을 짓는다 if((idx=fileName.indexOf(".")) != -1){ String left = fileName.substring(0, idx); String right = fileName.substring(idx); temp = left + "[" + cnt + "]" + right; }else{ temp = fileName + "[" + cnt + "]"; } tempFile = new File(realPath+temp); cnt++; } //실제 저장될 파일이름 저장 fileName = temp; return fileName; } public static String getSavedFileName(String originalFileName) { // 확장자 추출 String ext = ""; int lastDot = originalFileName.lastIndexOf('.'); if (lastDot != -1) { ext = originalFileName.substring(lastDot); // .pdf, .jpg 등 } // UUID 생성 + 확장자 붙이기 String savedFileName = UUID.randomUUID().toString() + ext; return savedFileName; } }