Java — How to delete a file or directory | Code Factory

Delete File using Java NIO’s Files.delete() (Recommended) — JDK 7+

package com.example.java.programming.file;import java.io.IOException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* @author code.factory
*
*/
public class DeleteFileExample {
public static void main(String... args) {
// File or Directory to be deleted
Path path = Paths.get("folder/folder1/test.txt");
try {
// Delete file or directory
Files.delete(path);
System.out.println("File or directory deleted successfully");
} catch (NoSuchFileException ex) {
System.out.printf("No such file or directory: %s\n", path);
} catch (DirectoryNotEmptyException ex) {
System.out.printf("Directory %s is not empty\n", path);
} catch (IOException ex) {
System.out.println(ex);
}
}
}
File or directory deleted successfully
// Delete file or directory if it exists
boolean isDeleted = Files.deleteIfExists(path);
if(isDeleted) {
System.out.println("File deleted successfully");
} else {
System.out.println("File doesn't exist");
}

Delete File in Java using File.delete method — JDK 6

package com.example.java.programming.file;import java.io.File;/**
* @author code.factory
*
*/
public class DeleteFileExample {
public static void main(String... args) {
// File to be deleted
File file = new File("folder/folder1/test.txt");
// Delete file
boolean isDeleted = file.delete();
if(isDeleted) {
System.out.println("File deleted successfully");
} else {
System.out.println("File doesn't exist");
}
}
}
File deleted successfully

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store