คลาสชื่อ ไฟล์ ของแพ็คเกจ java.io แสดงถึงไฟล์หรือไดเร็กทอรี (ชื่อพาธ) ในระบบ คลาสนี้มีเมธอดต่างๆ เพื่อดำเนินการต่างๆ กับไฟล์/ไดเร็กทอรี
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();
//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");
}
}
} ผลลัพธ์
Enter the path to create a directory: D:\test\myDirectories\ Enter the name of the desired a directory: sample_directory Directory created successfully
หากคุณตรวจสอบคุณสามารถสังเกตไดเร็กทอรีที่สร้างขึ้นเป็น −
