🛠️Backend/Spring

[Spring Boot] 프로젝트 실행 시 파일 존재 여부 확인 및 신규 파일 생성

뉴발자 2024. 3. 6.
728x90

 

 

 

 

 

 

 

 

 

 

 

 

 

 

[Spring Boot] 프로젝트 실행 시 파일 존재 여부 확인 및 신규 파일 생성
그림 1. Spring Boot

 

 

파일 존재 확인

FileApplication.java

@Slf4j
@SpringBootApplication
public class FileApplication {
    public static void main(String[] args) {
        // '파일.확장자'로 파일을 생성한다.
        String fileName = "파일.확장자";
        
        // 파일이 존재하지 않는다면 파일을 생성한다.
        if( !CreateFile.fileExists(fileName) ) {
            log.error("[error] 'fileName' 파일이 존재하지 않습니다.");

            CreateFile.createFile(fileName);

            return;
        }

        SpringApplication.run(FileApplication.class, args);
    }
}

 

 

파일 확인 및 생성

CreateFile.java

@Slf4j
public class CreateFile {
    // 파일 확인 함수
    public static boolean fileExists(String filePath) {
        File file = new File(filePath);
        return file.exists();
    }

    // 파일 생성 함수
    public static void createConfigFile(String filePath) {
        try {
            // config.yml 파일 생성
            String content = "테스트 파일";

            Files.write(Path.of(filePath), content.getBytes(), StandardOpenOption.CREATE);

            log.info("파일 생성 완료 !");
        } catch (IOException e) {
            log.error("error: " + e.getMessage());
        }
    }
}
728x90

 

 

테스트

파일 생성 전 폴더 구조는 다음과 같다.

[Spring Boot] 프로젝트 실행 시 파일 존재 여부 확인 및 신규 파일 생성 - 테스트
그림 2. 파일 생성 전 폴더 구조

 

프로젝트를 실행하면 아래와 같은 로그가 뜬다.

[Spring Boot] 프로젝트 실행 시 파일 존재 여부 확인 및 신규 파일 생성 - 테스트
그림 3. 파일이 없는 경우 프로젝트 실행 시 로그

 

'config.yml' 파일이 존재하지 않으므로 에러 로그를 발생시키고 파일을 생성해준다.

[Spring Boot] 프로젝트 실행 시 파일 존재 여부 확인 및 신규 파일 생성 - 테스트
그림 4. 파일 생성 후 폴더구조

 

 

 

 

 

 

 

 

 

 

728x90

댓글