Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

Java에서 Files 클래스를 활용한 디렉토리 생성 방법 – createDirectory()와 createDirectories() 완벽 가이드


Java Files 클래스란?

Java 7부터 Files 클래스가 새롭게 도입되었습니다. 이 클래스는 파일, 디렉토리 등 다양한 종류의 파일 시스템 객체를 다룰 수 있는 정적(static) 메소드들을 제공합니다.

그중 createDirectory() 메소드는 생성하고자 하는 디렉토리의 경로를 매개변수로 전달받아 해당 위치에 새로운 디렉토리를 만들어 줍니다.

createDirectory() 메소드로 디렉토리 생성하기

다음 Java 예제는 사용자로부터 디렉토리를 생성할 경로와 이름을 입력받은 후, 실제로 디렉토리를 생성하는 과정을 보여줍니다.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class Test {
    public static void main(String args[]) throws IOException {
        System.out.println("Enter the path to create a directory: ");
        Scanner sc = new Scanner(System.in);
        String pathStr = sc.next();
        System.out.println("Enter the name of the desired a directory: ");
        pathStr = pathStr + sc.next();
        // Path 객체 생성
        Path path = Paths.get(pathStr);
        // 디렉토리 생성
        Files.createDirectory(path);
        System.out.println("Directory created successfully");
    }
}

실행 결과

Enter the path to create a directory:
D:
Enter the name of the desired a directory:
sample_directory
Directory created successfully

파일 탐색기에서 직접 확인해 보면 아래와 같이 새로 생성된 디렉토리를 볼 수 있습니다.

Java에서 Files 클래스를 활용한 디렉토리 생성 방법 – createDirectory()와 createDirectories() 완벽 가이드

createDirectories() 메소드로 하위 디렉토리까지 한 번에 생성하기

createDirectories() 메소드는 지정한 디렉토리뿐만 아니라, 존재하지 않는 모든 상위(부모) 디렉토리까지 한꺼번에 생성해 줍니다.

다음 예제는 여러 단계로 중첩된 디렉토리 구조를 단 한 번의 호출로 생성합니다.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class Test {
    public static void main(String args[]) throws IOException {
        System.out.println("Enter the path to create a directory: ");
        Scanner sc = new Scanner(System.in);
        String pathStr = sc.next();
        System.out.println("Enter the name of the desired a directory: ");
        pathStr = pathStr + sc.next();
        // Path 객체 생성
        Path path = Paths.get(pathStr);
        // 디렉토리 생성
        Files.createDirectories(path);
        System.out.println("Directories created successfully");
    }
}

실행 결과

Enter the path to create a directory:
D:
Enter the name of the desired a directory:
sample/test1/test2/test3/final_folder
Directories created successfully

마찬가지로 파일 탐색기에서 확인해 보면, 기존에 존재하지 않던 상위 디렉토리들까지 모두 계층 구조로 생성된 것을 확인할 수 있습니다.

Java에서 Files 클래스를 활용한 디렉토리 생성 방법 – createDirectory()와 createDirectories() 완벽 가이드

두 메소드의 주요 차이점

  • createDirectory(): 상위 디렉토리가 존재하지 않으면 NoSuchFileException이 발생하며, 이미 같은 이름의 디렉토리가 있으면 FileAlreadyExistsException이 발생합니다.
  • createDirectories(): 필요한 상위 디렉토리를 자동으로 생성해 주며, 이미 디렉토리가 존재하더라도 오류 없이 정상적으로 처리됩니다.