Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีสร้างลำดับชั้นไดเรกทอรี (Directory Hierarchy) ใน Java

คลาสชื่อ File ของแพ็กเกจ java.io แทนไฟล์หรือไดเรกทอรี (path names) ในระบบ คลาสนี้มีเมธอดต่างๆ สำหรับดำเนินการกับไฟล์/ไดเรกทอรี

เมธอด mkdir() ของคลาสนี้ สร้างไดเรกทอรีด้วยพาธที่แทนโดยอ็อบเจกต์ปัจจุบัน

การสร้างลำดับชั้นไดเรกทอรี

เพื่อสร้างลำดับชั้นของไดเรกทอรีใหม่ คุณสามารถใช้เมธอด mkdirs() ของคลาสเดียวกัน เมธอดนี้สร้างไดเรกทอรีด้วยพาธที่แทนโดยอ็อบเจกต์ปัจจุบัน รวมถึงไดเรกทอรีพาเรนต์ที่ยังไม่มีอยู่

ตัวอย่าง

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();
        
        // สร้าง File object
        File file = new File(path);
        
        // สร้างไดเรกทอรี
        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:\test\myDirectories\
Enter the name of the desired a directory: sample_directory
Directory created successfully

หากตรวจสอบ คุณจะเห็นไดเรกทอรีที่สร้างขึ้น −

วิธีสร้างลำดับชั้นไดเรกทอรี (Directory Hierarchy) ใน Java