How to Delete Files using Java
Submitted by donbermoy on Monday, May 19, 2014 - 22:19.
Language
In this tutorial, we will create a program that can delete files using Java. We are done with creating files, appending, and reading data inside of a file.
So, now let's start this tutorial!
1. Open Notepad. Encode any data in there and save it to the same folder with your java program and named it as data.txt.
2. Open JCreator or NetBeans and make a java program with a file name of deleteFiles.java.
3. Import java.io package. Hence we will use an input/output in creating files. Import also javax.swing package because we will use the JOptionPane.showMessageDialog here.
4. In your main, initialize the data.txt that you have created a while ago for this file. This data.txt file is the file that we will going to delete.
5. Now, we will create an if-else statement that checks if the file is exists before deletion.
If the file doesn't exist:
Output:
Here's the full code of this tutorial:
Hope this program helps :)
Best Regards,
Engr. Lyndon R. Bermoy
IT Instructor/System Developer/Android Developer/Freelance Programmer
If you have some queries, feel free to contact the number or e-mail below.
Mobile: 09488225971
Landline: 826-9296
E-mail:[email protected]
Add and Follow me on Facebook: https://www.facebook.com/donzzsky
Visit and like my page on Facebook at: https://www.facebook.com/BermzISware
- import java.io.*;
- import javax.swing.*;
- if (file.exists())
- {
- // Use the delete method to delete the given file.
- file.delete();
- }
- else
- {
- }

- import java.io.*;
- import javax.swing.*;
- public class deleteFiles
- {
- {
- // When want to delete a file named data.txt
- // Checks if the file is exists before deletion.
- if (file.exists())
- {
- // Use the delete method to delete the given file.
- file.delete();
- } else
- {
- }
- }
- }
Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.
Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.
FOR YOUR OWN SAFETY, PLEASE:
1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.
Add new comment
- 81 views