아래 예제에서는 "c:\\fichier_log.log"라는 로그 파일과 "dossier_log" 폴더를 삭제합니다.
package com.codeurjava.File;
import java.io.File;
public class Delete_File
{
public static void main(String[] args)
{
try{
파일 파일 = new File("c:\\fichier.log");
if(file.delete()){
System.out.println(file.getName() + "가 삭제되었습니다.");
}else{
System.out.println("삭제 작업 실패");
}
파일 폴더 = 새 파일("c:\\dossier_log");
if(folder.delete()){
System.out.println(folder.getName() + "가 삭제되었습니다.");
}else{
System.out.println("삭제 작업 실패");
}
}catch(예외 e){
e.printStackTrace();
}
}
}
Runtime:
fichier_log.log 삭제됩니다.
dossier_log이 삭제되었습니다.
파일 경로를 직접 제공하여 파일이나 폴더를 삭제할 수도 있습니다. Files 클래스는 delete(Path) 경로 경로를 삭제하고, 그렇지 않으면 실패할 경우 예외를 throw합니다. 파일이 존재하지 않는 경우 NoSuchFileException이 발생합니다. 예외를 검색하고 다음과 같이 삭제가 실패한 이유를 확인할 수 있습니다.
try {리소스:
Files.delete(path);
} catch (NoSuchFileException x) {
System.err.format("%s:" + "경로를 찾을 수 없음: %n", 경로);
} catch (DirectoryNotEmptyException x) {
System.err.format("%s은(는) 비어 있지 않습니다.%n", 경로);
} catch (IOException x) {
// 권한 문제
System.err.println(x);
}
https://docs.oracle.com/javase/tutorial/essential/io/delete.html
Commentaires (12)
Connectez-vous pour commenter
Rejoignez la discussion et partagez vos connaissances avec la communauté
Excellent tutoriel !
N'hésitez pas si vous avez des questions.