Java에서 파일을 삭제하려면 Files 클래스의 delete() 메서드를 사용할 수 있습니다. 또한 File 클래스의 인스턴스 객체에 대해 delete() 메서드를 호출하는 방법도 있습니다.
각 방법을 예제 코드와 함께 자세히 살펴보겠습니다.
Files 클래스로 파일 삭제하기
아래 코드 예제는 Files 클래스를 사용하여 파일을 삭제하는 방법을 보여줍니다.
import java.io.IOException;
import java.nio.file.*;
public class DeleteFile {
public static void main(String[] args) {
Path path = FileSystems.getDefault().getPath("./src/test/resources/newFile.txt");
try {
Files.delete(path);
} catch (NoSuchFileException x) {
System.err.format("%s: no such" + " file or directory%n", path);
} catch (IOException x) {
System.err.println(x);
}
}
}
위 코드는 ./src/test/resources/ 디렉터리에 있는 newFile.txt라는 이름의 파일을 삭제합니다.
여러 개의 catch() 블록을 사용하면 파일 삭제 과정에서 발생할 수 있는 다양한 오류를 각각 처리할 수 있습니다. 파일이 존재하지 않으면 NoSuchFileException이 발생하고, 그 외의 입출력 오류는 IOException으로 잡아 처리합니다.
File 클래스로 파일 삭제하기
Files 클래스의 delete() 메서드 대신, File 클래스의 인스턴스 객체에 대해 delete() 메서드를 호출하는 방법도 사용할 수 있습니다.
예제:
import java.io.File;
public class DeleteFile {
public static void main(String[] args) {
File myFile = new File("./src/test/resources/newFile.txt");
if (myFile.delete()) {
System.out.println("Deleted the file: " + myFile.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}
File 클래스의 delete() 메서드는 삭제 성공 여부를 boolean 값으로 반환하므로, 위 예제처럼 if문으로 결과를 확인하여 성공/실패 메시지를 출력할 수 있습니다.
파일이 존재할 때만 안전하게 삭제하기
다음 코드는 파일을 삭제하기 전에 deleteIfExists() 메서드를 사용합니다.
import java.io.IOException;
import java.nio.file.*;
public class DeleteFile {
public static void main(String[] args) {
Path path = FileSystems.getDefault().getPath("./src/test/resources/newFile.txt");
try {
Files.deleteIfExists(path);
} catch (IOException x) {
System.err.println(x);
}
}
}
위 코드 예제에서 파일이 존재하지 않더라도 NoSuchFileException 예외가 발생하지 않습니다. 따라서 파일의 존재 여부가 불확실한 경우에는 이 방법이 더 안전하고 편리합니다.
디렉터리 삭제하기
앞서 소개한 코드를 그대로 사용하여 폴더(디렉터리)도 삭제할 수 있습니다.
단, 폴더가 비어 있지 않으면 DirectoryNotEmptyException이 발생하므로, 해당 예외를 명시적으로 catch하여 처리해야 합니다.
import java.io.IOException;
import java.nio.file.*;
public class DeleteFile {
public static void main(String[] args) {
Path path = FileSystems.getDefault().getPath("./src/test/resources");
try {
Files.deleteIfExists(path);
} catch (NoSuchFileException x) {
System.err.format("%s: no such" + " file or directory%n", path);
} catch (DirectoryNotEmptyException x) {
System.err.format("%s not empty%n", path);
} catch (IOException x) {
System.err.println(x);
}
}
}
마무리
정리하면, Java에서 파일을 삭제하는 대표적인 방법은 두 가지입니다. NIO API인 Files.delete()와 전통적인 IO API인 File.delete()입니다. 파일 존재 여부를 먼저 확인하고 싶다면 Files.deleteIfExists()를 사용하고, 비어 있지 않은 디렉터리를 삭제할 때는 반드시 DirectoryNotEmptyException 처리를 추가해야 합니다.
- Java에서 파일을 생성하는 방법
- Java에서 파일에 데이터를 쓰는 방법