(File객체 mkdir) FileNotFoundException

pickylemon·2024년 5월 12일

Exception 모음

목록 보기
13/31

상황

게시판에 파일 업로드 기능 구현 중,
파일 저장 경로 문자열을 인자로 주고 File객체를 생성 후,
MultipartFile에서 해당 File로 transfer하는 과정에서 에러 발생.

  • C:\\dev\\workspace\\까지는 실제 존재하는 디렉토리
  • 오늘날짜를 기준으로 동적으로 디렉토리를 생성해서 파일을 구분해서 저장하려는 목적
public class FileUtil {
	//파일을 물리적으로 저장하는 역할을 하는 클래스
	private static String SAVE_PATH = "C:\\dev\\workspace\\attFile\\";
	
	public File saveFiles(MultipartFile mf) {

		File destfile = new File(getSavePath()); //'오늘' 날짜를 기준으로 동적으로 생성한 경로로 File 객체 생성'
		
		try {
			
			if(!destfile.exists()) {
				destfile.mkdir(); //해당 경로의 파일이 존재하지 않으면 create
			}
      ...
    }
      
      
    /**
	 * 파일의 저장 경로(SAVE_PATH\YYYY\MM\DD)를 구하는 메서드
	 * @return
	 */
	private String getSavePath() {
		String date = LocalDateTime.now()
				.format(DateTimeFormatter.ISO_DATE)
				.replaceAll("-", "//");
		
		return SAVE_PATH + date;
	}  
      
 }

원인 및 해결

  • File클래스의 mkdir과 mkdirs 메서드의 차이에서 발생

mkdir()

  • Creates the directory named by this abstract pathname.
  • dir. 즉, 단수형이다. 하나의 하위 디렉토리만 생성할 수 있음.
  • 생성하려는 디렉토리의 상위 디렉토리들은 이미 존재해야한다.

mkdirs()

  • Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.
  • dirs. 복수형이다. 상위 디렉토리가 없으면 상위디렉토리까지 만든다.

즉, 날짜를 기반으로 디렉토리를 동적으로 생성하려는 목적이므로 mkdirs()로 코드를 수정하니 에러를 바로 잡을 수 있었다. (당연히 디렉토리도 잘 생성됨)

profile
안녕하세요

0개의 댓글