폴더(디렉토리) 생성
Java에서 폴더를 생성하는 방법은 간단합니다. File 클래스에 정의되어 있는 mkdir() 메서드를 사용하면 됩니다.
다음 소스 코드는 D드라이브에 Directory폴더를 생성하는 예제입니다.
public static void main(String args[])
{
File file = new File("D:\\Directory");
if (file.mkdir() == true) {
System.out.println("디렉토리가 생성되었습니다.");
} else {
System.out.println("디렉토리를 생성하지 못했습니다.");
}
}
mkdir() 메서드는 폴더가 성공적으로 생성되면 true를 반환하고 그렇지 않으면 false를 반환합니다.
하지만 폴더가 이미 존재하는 경우 false가 아닌 FileAlreadyExistsException 예외가 발생합니다. 따라서 exists() 메서드를 사용하여 폴더가 존재하는지 확인 후 mkdir() 메서드를 호출합니다.
public static void main(String args[])
{
File file = new File("D:\\Directory");
if(file.exists()) {
if (file.mkdir() == true) {
System.out.println("디렉토리가 생성되었습니다.");
} else {
System.out.println("디렉토리를 생성하지 못했습니다.");
}
} else {
System.out.println("디렉토리가 존재합니다.");
}
}
중첩된 폴더 생성
mkdir() 메서드의 단점은 중첩된 폴더구조에서 상위 폴더가 존재하지 않으면 NoSuchFileException 예외가 발생합니다.
만약, 다음 예제처럼 D드라이브에 Directory 폴더가 없는 경우 SubDirectory 폴더의 상위 폴더가 없으므로 NoSuchFileException 예외가 발생합니다.
public static void main(String args[])
{
File file = new File("D:\\Directory\\SubDirectory");
if(file.exists()) {
if (file.mkdir() == true) {
System.out.println("디렉토리가 생성되었습니다.");
} else {
System.out.println("디렉토리를 생성하지 못했습니다.");
}
} else {
System.out.println("디렉토리가 존재합니다.");
}
}
방법 1. mkdirs 메서드
위 문제를 해결하는 방법으로 File 클래스의 mkdirs() 메서드를 사용합니다. mkdirs() 메서드는 상위 폴더가 없는 경우 상위 폴더를 생성하고 중첩된 폴더도 생성합니다.
반환 결과는 mkdir() 메서드와 동일합니다.
public static void main(String args[])
{
File file = new File("D:\\Directory\\SubDirectory");
if(file.exists()) {
if (file.mkdirs() == true) {
System.out.println("디렉토리가 생성되었습니다.");
} else {
System.out.println("디렉토리를 생성하지 못했습니다.");
}
} else {
System.out.println("디렉토리가 존재합니다.");
}
}
방법 2. createDirectories 메서드
또 다른 방법으로 java.nio.file.Files 클래스의 createDirectories() 메서드를 사용합니다. 상위 폴더가 존재하지 않으면 자동으로 생성해주며 폴더가 존재하더라도 예외가 발생하지 않습니다.
따라서 exists() 메서드를 호출할 필요가 없습니다.
public static void main(String args[])
{
File file = new File("D:\\Directory\\SubDirectory");
Files.createDirectories(file.toPath());
}
'Java' 카테고리의 다른 글
[Java]날짜 정렬 방법 (0) | 2022.08.11 |
---|---|
[Java]LocalDate 비교 방법(날짜 비교 방법) (0) | 2022.08.11 |
[Java]인터페이스의 정적 메서드 (0) | 2022.06.27 |
[Java]중첩 인터페이스 및 내부 인터페이스(Nested Interface and Inner Interface) (0) | 2022.06.27 |
[Java]오토박싱과 언박싱(Autoboxing and Unboxing) (0) | 2022.06.22 |
댓글