TIL

[250305 TIL] 파일 이름 바꾸기 리팩토링

도원좀비 2025. 3. 6. 21:01

While 반복문에서의  return break continue 의 차이

제어문 동작방식
return 메서드를 즉시 종료하고 호출한 곳으로 돌아감 (루프뿐만 아니라 메서드 자체를 끝냄)
break 현재 while 루프를 완전히 종료하고 루프 다음 코드로 이동
continue 현재 반복만 건너뛰고 while 문의 처음으로 돌아가서 다음 반복 실행

 

 

filerenamer의 리팩토링 후 유효성 검사를 진행했다.

FileRenamer.java -->> RenameFile.java로 변

(이전코드)

// 여러 개 파일 Batch Rename 처리
private void batchRenameFiles() {
    String baseName;
    int startNumber;

    //  공통 이름 입력
    while (true) {
        System.out.print("변경할 파일의 공통 이름 입력: ");
        baseName = scanner.nextLine();
        if (validFile.isValidFileName(baseName)) {
            break;
        }
    }

    //  시작 번호 입력
    while (true) {
        System.out.print("시작 번호 입력: ");
        if (scanner.hasNextInt()) {
            startNumber = scanner.nextInt();
            scanner.nextLine(); // 개행 문자 제거
            if (startNumber >= 0) {
                break;
            }
        } else {
            scanner.nextLine(); // 잘못된 입력 제거
        }
        System.out.println("시작 번호는 0 이상이어야 합니다.");
    }

    File folder = new File(directoryPath);
    File[] files = folder.listFiles();

    //  변경할 파일이 없을 경우 다시 입력 요청
    if (files == null || files.length == 0) {
        System.out.println("변경할 파일이 없습니다. 다시 입력하세요.");
        batchRenameFiles();
        return;
    }

    int count = startNumber;
    for (File file : files) {
        if (file.isFile()) {
            String extension = "";
            int dotIndex = file.getName().lastIndexOf(".");
            if (dotIndex != -1) {
                extension = file.getName().substring(dotIndex);
            }

            String newName = baseName + "_" + count + extension;
            File newFile = new File(directoryPath, newName);

            // 🔹 기존에 같은 이름의 파일이 있는지 확인
            if (newFile.exists()) {
                System.out.println("⚠이미 같은 이름의 파일이 존재합니다: " + newName);
                continue;
            }

            rename(file, newFile);
            count++;
        }
    }
    System.out.println("Batch Rename 완료!");
}

 

(이후 코드)

// 4. 여러 파일 이름 한꺼번에 변경
public void renameMultipleFiles() {
    while (true) {
        System.out.print("변경할 파일의 공통 이름 입력: ");
        String baseName = scanner.nextLine();

        System.out.print("시작 번호 입력: ");
        int startNumber = 0;

        if (scanner.hasNextInt()) {
            startNumber = scanner.nextInt();
            scanner.nextLine(); // 개행 문자 제거

            if (!validFile.isValidNumber(startNumber)) {
                scanner.nextLine(); // 잘못된 입력 제거
                continue; // 메시지 출력 없이 다시 입력받음
            }
        }else {
            System.out.println("양의 정수를 입력하세요");
            scanner.nextLine();
            continue;
        }



        File folder = new File(directoryPath);
        File[] files = folder.listFiles();
        int count = startNumber;
        boolean anyFileRenamed = false; // 변경된 파일이 하나라도 있는지 확인

        // 파일 이름 변경
        for (File file : files) {
            if (file.isFile()) {
                String newName = count++ + "_" + baseName;

                if (!fileUtils.RunRename(file.getName(), newName)) {
                    System.out.println("파일 변경 실패 (건너뜀): " + file.getName());
                    continue; // 실패한 파일을 무시하고 다음 파일로 이동
                }

                anyFileRenamed = true; // 최소한 하나의 파일이 변경됨
            }
        }

        if (anyFileRenamed) {
            break; // 하나라도 변경 성공한 경우 루프 종료
        }
    }
}

 

ValidFile.java에 추가 코드

// 숫자 유효성 검사
public boolean isValidNumber(Integer number) {
    if (number == null) {
        System.out.println("숫자가 입력되지 않았습니다.");
        return false;
    }
    if (number < 0) {
        System.out.println("유효하지 않은 숫자 입력 : " + number);
        return false;
    }
    return true;
}

 

FileUtils.java로 rename메서드를 이동

// 파일 이름 변경 실행
public boolean RunRename(String oldName, String newName ) {
    File oldFile = new File(directoryPath, oldName);
    File newFile = new File(directoryPath, newName);

    // 파일 유효성 검사
    if (!validFile.isValidFile(oldFile.getPath())) {
        System.out.println("존재하지 않는 파일입니다 : " + oldName);
        return false;
    }
    // 파일 중복 검사
    if (newFile.exists()){
        System.out.println("이미 같은 이름의 파일이 존재합니다 : " + newName);
        return false;
    }
    // 파일 이름 유효성 검사 (공백 + 금지된 문자 체크)
    if (!validFile.isValidFileName(newName)){
        return false;
    }


    // 파일 이름 변경 실행
    if (oldFile.renameTo(newFile)) {
        System.out.println("파일 이름 변경 성공: " + oldName + " → " + newName);
        return true;
    } else {
        System.out.println("이름 변경 실패: " + oldName + " → " + newName);
        return false;
    }
}

메서드의 역할을 확실히 나누면서 추상화를 더 균일하게 해보았다.

 

 

Main.java를 흐름을 알 수 있게 수정

(이전코드)

// 파일 이름 변경 실행
public boolean RunRename(String oldName, String newName ) {
    File oldFile = new File(directoryPath, oldName);
    File newFile = new File(directoryPath, newName);

    // 파일 유효성 검사
    if (!validFile.isValidFile(oldFile.getPath())) {
        System.out.println("존재하지 않는 파일입니다 : " + oldName);
        return false;
    }
    // 파일 중복 검사
    if (newFile.exists()){
        System.out.println("이미 같은 이름의 파일이 존재합니다 : " + newName);
        return false;
    }
    // 파일 이름 유효성 검사 (공백 + 금지된 문자 체크)
    if (!validFile.isValidFileName(newName)){
        return false;
    }


    // 파일 이름 변경 실행
    if (oldFile.renameTo(newFile)) {
        System.out.println("파일 이름 변경 성공: " + oldName + " → " + newName);
        return true;
    } else {
        System.out.println("이름 변경 실패: " + oldName + " → " + newName);
        return false;
    }
}

 

(이후코드)

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String exit = "";

        while (!exit.equalsIgnoreCase("exit")) { // "exit" 입력 전까지 반복
            // 1. 디렉터리 입력 후 확인
            System.out.print("파일이 있는 디렉터리 경로 입력 (종료하려면 'exit' 입력): ");
            String directoryPath = scanner.nextLine();

            if (directoryPath.equalsIgnoreCase("exit")) {
                break; // "exit" 입력 시 while 루프 종료
            }

            RenameFile renameFile = new RenameFile(directoryPath);

            // 2. 파일 이름 변경 작업 카테고리 고르기
            int choice = renameFile.selectRenameCategory();

            // 3. 선택한 작업 실행
            if (choice == 1) {
                renameFile.renameSingleFile();
            } else if (choice == 2) {
                renameFile.renameMultipleFiles();
            }

        }

        System.out.println("프로그램을 종료합니다.");
        scanner.close();
    }
}

 

기존에 너무 축약되어있는 코드를 메인클래스만 보아도 진행과정을 알 수 있도록 수정하였다.

 

앞으로 진행 할 작업

  1. 특정 확장자 파일만 변경(필터링을 통해서 진행)
  2. 수정 후 파일명 미리보기 기능 추가
  3. 로그 기능 추가
  4. 예외처리 추가
  5. 파일 이름 일괄 수정 패턴 추가