The example below will delete a log file named "c:\\fichier_log.log" and a folder "dossier_log".
package com.codeurjava.File;
import java.io.File;
public class Delete_File
{
public static void main(String[] args)
{
try{
File file = new File("c:\\fichier.log");
if(file.delete()){
System.out.println(file.getName() + " is deleted.");
}else{
System.out.println("Delete operation failed");
}
File folder = new File("c:\\dossier_log");
if(folder.delete()){
System.out.println(folder.getName() + " is deleted.");
}else{
System.out.println("Delete operation failed");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
Runtime:
fichier_log.log is deleted.
dossier_log is deleted.
You can also delete files or folders by providing the file path directly. The Files class provides the method delete(Path) which deletes the Path path otherwise throws an exception if it fails. If the file does not exist, a NoSuchFileException is raised. You can retrieve the exception and determine why the deletion failed like this:
try {Resources:
Files.delete(path);
} catch (NoSuchFileException x) {
System.err.format("%s:" + "path not found %n", path);
} catch (DirectoryNotEmptyException x) {
System.err.format("%s is not empty %n", path);
} catch (IOException x) {
// permission issues
System.err.println(x);
}
https://docs.oracle.com/javase/tutorial/essential/io/delete.html
Commentaires (0)
Laisser un commentaire
Connectez-vous pour commenter
Rejoignez la discussion et partagez vos connaissances avec la communauté
Chargement des commentaires...