Java 폴더(디렉터리) 생성

 

Summry

본 문서에서는 JAVA로 디렉터리 생성 방법을 정리한다.

send me email if you have any questions.


방법

해당 위치에 원하는 폴더가 없을 경우 새로이 폴더를 하나 만들어주는 방법은 File클래스안의 mkdir이라는 메서드를 활용하여 간단히 구현할 수 있다.

example code

// 디렉터리가 없다면 생성
File Folder = new File(path);
if (!Folder.exists()) {
    try {
    Folder.mkdir(); // 디렉터리 생성.
    } catch (Exception e) {
    e.getStackTrace();
    }
} else {
}

아래의 코드는 이미지 업로드 API에서 업로드할 위치에 디렉터리가 없다면 생성하는 예제

@Operation(summary = "게시글 이미지 업로드 API")
  @PostMapping("/postImage")
  public int uploadPostImage(@RequestPart List<MultipartFile> files, HttpServletResponse res)
      throws Exception {
    String originName = "";
    String saveName = "";
    long size;
    int post_index = communityService.checkPostIndex();
    String path = "/home/ubuntu/testproject/src/main/resources/static/images/post/";
    UUID uuid = UUID.randomUUID();

    path += post_index;

    // 디렉터리가 없다면 생성
    File Folder = new File(path);
    if (!Folder.exists()) {
      try {
        Folder.mkdir(); // 디렉터리 생성.
      } catch (Exception e) {
        e.getStackTrace();
      }
    } else {
    }

    for (MultipartFile file : files) {
      originName = file.getOriginalFilename();
      size = file.getSize();
      
      // DB에 저장할 경로(static resource 조회를 위함)
      path = "/static/images/post/" + post_index;

      // filename의 중복을 제거하기 위해 UUID 사용
      saveName = uuid.toString() + "_" + originName;

      path = path + "/" + saveName;
      int result = communityService.uploadPostImage(null, post_index, originName, size, path);
      if (result > 0) {
        // 실제 저장되는 절대 경로
        path = "/home/ubuntu/testproject/src/main/resources/static/images/post/" + post_index + "/" + saveName;
        
        file.transferTo(new File(path));
      } else {
        res.setStatus(StatusCode.serverErr);
        return StatusCode.serverErr;
      }
    }

    res.setStatus(StatusCode.Created);
    return StatusCode.Created;
  }

Reference

[Java] 자바로 폴더(디렉토리) 생성하기 - 코딩팩토리