Java 7부터 File.02s 클래스가 도입된 이후로 여기에는 파일, 디렉토리 또는 기타 유형의 파일에서 작동하는 (정적) 메소드가 포함됩니다.
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(); //Creating a path object Path path = Paths.get(pathStr); //Creating a directory 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
확인하면 생성된 디렉토리를 -
로 볼 수 있습니다.
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(); //Creating a path object Path path = Paths.get(pathStr); //Creating a directory 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 Directory created successfully
확인하면 생성된 디렉토리를 -
로 볼 수 있습니다.