- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Delete the file or directory in Java
The method java.io.File.delete() can be used to delete the file or directory with the required abstract path name. This method requires no parameters and it returns true on the successful deletion of the file or the directory and false otherwise.
A program that demonstrates this is given as follows −
Example
import java.io.File; public class Demo { public static void main(String[] args) { try { File file = new File("demo1.txt"); file.createNewFile(); System.out.println("File: " + file); boolean flag = file.delete(); System.out.println("The File is deleted? " + flag); } catch(Exception e) { e.printStackTrace(); } } }
The output of the above program is as follows −
Output
File: demo1.txt The File is deleted? true
Now let us understand the above program.
The file with the required abstract path name is deleted using the method java.io.File.delete(). Then the boolean value returned by this method is printed. A code snippet that demonstrates this is given as follows −
try { File file = new File("demo1.txt"); file.createNewFile(); System.out.println("File: " + file); boolean flag = file.delete(); System.out.println("The File is deleted? " + flag); } catch(Exception e) { e.printStackTrace(); }
- Related Articles
- Java Program to delete file or directory
- Delete file or directory on termination in Java
- Java Program to delete a file or directory when the program ends
- Rename file or directory in Java
- Check for file or directory in Java
- Determine if file or directory exists in Java
- Mark file or directory Read Only in Java
- Delete a directory in Java
- Get the absolute path for the directory or file in Java
- Determine if File or Directory is hidden in Java
- Java Program to rename a file or directory
- Java Program to get the name of the parent directory of the file or directory
- Specify a path for a file or a directory in Java
- Java Program to get the File object with the absolute path for the directory or file
- Java Program to get name of specified file or directory

Advertisements