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

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

If You Lost Your Site, Could You Become A Python Developer?

Virtual Machines on Microsoft Azure- A Detailed Guide for Beginners

Managing Interrupt in Virtio-PCI

Implement the oncept of template in python and Implement the concept of the do-while loop in python

Building Custom Resolvers with Strapi

Game Assets via Filebase

How to monitor Jenkins metrics using Prometheus & Grafana?

Ehcache Configuration in Spring Boot

configure ehcache in spring boot

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
Code Factory

Code Factory

More from Medium

Exception handling In Java.

Multithreading Concept in JAVA

How to create a system for Pet Care Store in Java?

Decoding The JVM Architecture — Here’s How JVM Works