Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách tạo hệ thống thư mục phân cấp sử dụng Java


Class File của java.io đại diện file hoặc directory (path names). Cung cấp các phương thức thao tác file/directory.

Phương thức mkdir() tạo directory với path của object hiện tại.

Tạo hệ thống thư mục phân cấp

Để tạo hierarchy thư mục mới, dùng phương thức mkdirs() của class đó. Phương thức này tạo directory với path của object hiện tại, bao gồm cả parent directories chưa 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");       }    } }

Kết quả

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

Kiểm tra sẽ thấy thư mục tạo như sau:

Cách tạo hệ thống thư mục phân cấp sử dụng Java