Computer >> Máy Tính >  >> Lập trình >> Java

Làm thế nào để tạo Thư mục bằng cách sử dụng các phương pháp tiện ích Tệp trong Java?

Kể từ khi Java 7, lớp File.02s đã được giới thiệu, lớp này chứa các phương thức (tĩnh) hoạt động trên tệp, thư mục hoặc các loại tệp khác.

createDirectory () phương pháp của Tệp lớp chấp nhận đường dẫn của thư mục bắt buộc và tạo một thư mục mới.

Ví dụ

Ví dụ Java sau đây đọc đường dẫn và tên của thư mục sẽ được tạo, từ người dùng và tạo nó.

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");
   }
}

Đầu ra

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

Nếu bạn xác minh, bạn có thể thấy thư mục được tạo là -

Làm thế nào để tạo Thư mục bằng cách sử dụng các phương pháp tiện ích Tệp trong Java?

createDirectories () phương thức tạo thư mục nhất định bao gồm cả thư mục mẹ không tồn tại.

Ví dụ

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");  
   }
}

Đầ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

Nếu bạn xác minh, bạn có thể thấy thư mục được tạo là -

Làm thế nào để tạo Thư mục bằng cách sử dụng các phương pháp tiện ích Tệp trong Java?