Java에서 새 폴더를 만드는 방법
Java에서는 다음을 사용할 수 있습니다. 파일 객체 새 폴더나 디렉터리를 만듭니다. 그만큼 Java의 파일 클래스 디렉토리나 폴더를 만들거나 생성할 수 있는 방법을 제공합니다. 우리는 mkdir() 의 방법 파일 새로운 폴더를 생성하는 클래스입니다.
디렉토리를 생성하려면 먼저 File 클래스의 인스턴스를 생성하고 해당 인스턴스에 매개변수를 전달해야 합니다. 이 매개변수는 이를 생성해야 하는 디렉터리의 경로입니다. 그 후에는 mkdir() 해당 파일 객체를 사용하는 메서드입니다.
mkdir() 메서드를 사용하여 디렉터리나 폴더를 생성해 보겠습니다. 자바 프로그램.
CreateFolder.java
//Import file class import java.io.File; //Import Scanner class import java.util.Scanner; public class CreateFolder { //Main() method start public static void main(String args[]) { //Using Scanner class to get the path from the user where he wants to create a folder. System.out.println('Enter the path where you want to create a folder: '); Scanner sc = new Scanner(System.in); String path = sc.next(); //Using Scanner class to get the folder name from the user System.out.println('Enter the name of the desired a directory: '); path = path+sc.next(); //Instantiate the File class File f1 = new File(path); //Creating a folder using mkdir() method boolean bool = f1.mkdir(); if(bool){ System.out.println('Folder is created successfully'); }else{ System.out.println('Error Found!'); } } } 산출:
해당 위치로 이동하면 다음과 같이 생성된 폴더가 표시됩니다.
참고: 사용할 수 없는 경로를 입력하면 mkdir() 메서드는 폴더를 생성하지 않고 제어 흐름을 else 부분으로 전달합니다.
새 폴더의 계층 구조 생성
mkdir() 메서드의 단점은 mkdirs() 메서드로 해결됩니다. 그만큼 mkdirs() 방법은 그보다 더 강력하다 mkdir() 방법. mkdirs() 메서드는 새 폴더 또는 디렉터리의 계층 구조를 만듭니다. mkdir() 메소드와 동일한 방식으로 폴더를 생성하지만, 존재하지 않는 상위 폴더도 생성합니다.
mkdirs() 메서드가 mkdir() 메서드와 어떻게 다른지 이해하기 위해 예를 들어 보겠습니다.
CreateFolderHierarchy.java
import java.io.File; import java.util.Scanner; public class CreateFolderHierarchy { //main() method start public static void main(String args[]) { //Using Scanner class to get the path from the user where he wants to create a folder. System.out.println('Enter the path where you want to create a folder: '); Scanner sc = new Scanner(System.in); String path = sc.next(); //Using Scanner class to get the folder name from the user System.out.println('Enter the name of the desired a directory: '); path = path+sc.next(); //Instantiate the File class File f1 = new File(path); //Creating a folder using mkdirs() method boolean bool2 = f1.mkdirs(); if(bool2){ System.out.println('Folder is created successfully'); }else{ System.out.println('Error Found!'); } } } 산출:
원하는 위치에 접속하면 생성된 폴더가 보입니다. 사용자가 사용할 수 없는 위치를 입력하면 mkdirs()는 시스템에 존재하지 않는 모든 상위 폴더를 생성하여 해당 위치를 사용할 수 있게 만듭니다.