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

Làm thế nào để tạo một hệ thống phân cấp thư mục bằng Java?

Lớp có tên Tệp của gói java.io đại diện cho một tệp hoặc thư mục (tên đường dẫn) trong hệ thống. Lớp này cung cấp các phương thức khác nhau để thực hiện các thao tác khác nhau trên tệp / thư mục.

mkdir () phương thức của lớp này tạo một thư mục với đường dẫn được đại diện bởi đối tượng hiện tại.

Tạo phân cấp thư mục

Để tạo hệ thống phân cấp các thư mục mới, bạn có thể sử dụng phương pháp mkdirs () của cùng một lớp. Phương thức này tạo thư mục với đường dẫn được đại diện bởi đối tượng hiện tại, bao gồm cả các thư mục mẹ không tồn tại.

Ví dụ

import java.io.File;
import java.util.Scanner;
public class CreateDirectory {
   public static void main(String args[]) {
      System.out.println("Enter the path to create a directory: ");
      Scanner sc = new Scanner(System.in);
      String path = sc.next();
      System.out.println("Enter the name of the desired a directory: ");
      path = path+sc.next();
      //Creating a File object
      File file = new File(path);
      //Creating the directory
      boolean bool = file.mkdirs();
      if(bool) {
         System.out.println("Directory created successfully");
      }else {
         System.out.println("Sorry couldnt create specified directory");
      }
   }
}

Đầu ra

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

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

Làm thế nào để tạo một hệ thống phân cấp thư mục bằng Java?