Từ Java 7, lớp Files được giới thiệu chứa các method static thao tác trên file, thư mục, các loại file khác. (Lưu ý: bài gốc ghi "File.02s class" là lỗi chính tả của "Files class")
Phương thức createDirectory() của lớp Files chấp nhận path thư mục cần tạo và tạo thư mục mới.
Ví dụ 1 - Tạo thư mục đơn với Files.createDirectory()
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 = Paths.get(pathStr);
Files.createDirectory(path);
System.out.println("Directory created successfully");
}
}
Đầu ra
Enter the path to create a directory: D: Enter the name of the desired a directory: sample_directory Directory created successfully
Kiểm tra thư mục đã tạo:

Ví dụ 2 - Tạo thư mục phân cấp với 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 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 = Paths.get(pathStr);
Files.createDirectories(path);
System.out.println("Directories created successfully");
}
}
Đầu ra
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
Kiểm tra thư mục đã tạo:
