Java 7 Files 클래스가 도입된 이후로 여기에는 파일, 디렉토리 또는 기타 유형의 파일에서 작동하는 (정적) 메소드가 포함됩니다.
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 Demo {
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 required directory hierarchy: ");
pathStr = pathStr+sc.next();
//Creating a path object
Path path = Paths.get(pathStr);
//Creating a directory
Files.createDirectories(path);
System.out.println("Directory hierarchy created successfully");
}
} 출력
Enter the path to create a directory: D: Enter the required directory hierarchy: sample1/sample2/sapmle3/final_directory Directory hierarchy created successfully
확인하면 생성된 디렉토리 계층 구조를 관찰할 수 있습니다. -

File의 mkdirs() 메서드를 사용하여 새 디렉터리의 계층 구조를 만들 수도 있습니다. 이 메서드는 존재하지 않는 상위 디렉터리를 포함하여 현재 개체가 나타내는 경로로 디렉터리를 만듭니다.
예
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Demo {
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 required directory hierarchy: ");
pathStr = pathStr+sc.next();
//Creating a File object
File file = new File(pathStr);
//Creating the directory
boolean bool = file.mkdirs();
if(bool){
System.out.println("Directory created successfully");
}else{
System.out.println("Sorry couldn't create specified directory");
}
}
} 출력
Enter the path to create a directory: D Enter the required directory hierarchy: sample1/sample2/sample3/final_directory
확인하면 생성된 디렉토리 계층 구조를 관찰할 수 있습니다. -
