Java Directory 존재여부 체크 및 생성

2024. 11. 30. 07:25Java

File의 exists(), isDirectory() 사용

import java.io.File;

public class DirectoryCheck {
    public static void main(String[] args) {
        // Specify the directory path
        String directoryPath = "/path/to/directory";

        // Create a File object for the specified path
        File directory = new File(directoryPath);

        // Check if the path exists and is a directory
        if (directory.exists() && directory.isDirectory()) {
            System.out.println("The directory exists.");
        } else {
            System.out.println("The directory does not exist.");
        }
    }
}

디렉토리 없은 경우 생성

mkdir(): 지정된 디렉토리만 생성, 부모 디렉토리가 없으면 Fail
mkdirs(): 부모 디렉토리까지 생성

import java.io.File;

public class DirectoryCheckAndCreate {
    public static void main(String[] args) {
        // Specify the directory path
        String directoryPath = "/path/to/directory";

        // Create a File object for the specified path
        File directory = new File(directoryPath);

        // Check if the path exists and is a directory
        if (directory.exists()) {
            System.out.println("The directory already exists.");
        } else {
            // Try to create the directory
            if (directory.mkdirs()) {
                System.out.println("The directory was successfully created.");
            } else {
                System.out.println("Failed to create the directory.");
            }
        }
    }
}