In this quick tutorial, we will learn how to delete a file in Java.
We will see two ways to delete a file in Java:
- Delete the file using the delete() method of java.io.File class
- Delete file using Files.delete(Path) method of Java NIO
1. Delete File using File.delete() Method
- Create a file named "sample.txt" in the directory "C://workspace'.
- Create a File class object and pass the file absolute location path.
- call delete() method of file object to delete "sample.txt" file from directory "C://workspace"
- delete() method returns true if and only if the file or directory is successfully deleted; false otherwise.
- Observe the directory whether the file is deleted or not.
import java.io.File;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This Java program demonstrates how to delete a file in Java.
* @author javaguides.net
*/
public class DeleteFileExample {
private static final Logger LOGGER = LoggerFactory
.getLogger(DeleteFileExample.class);
public static void main(String[] args) {
deleteFile();
}
public static void deleteFile() {
File file = new File("C://workspace/sample.txt");
if (file.delete()) {
LOGGER.info(file.getName() + "created !!");
} else {
LOGGER.info("Delete operation failed");
}
}
}
2. Delete File using Java NIO’s Files.delete()
It is recommended to use Java NIO’s Files.delete() method to delete the file in Java:
import java.io.IOException;
import java.nio.file.*;
public class DeleteFileExample {
public static void main(String[] args) throws IOException {
// File or Directory to be deleted
Path path = Paths.get("./demo.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);
}
}
}
Reference
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course
Comments
Post a Comment