to delete a file i always use
public void DeleteFile ()
{
File erase = new File ("Filename.txt");
erase.delete (); //deleting the file Statistics
JOptionPane.showMessageDialog (infoPane, "The file has been deleted");
}
scheppy
Junior Poster in Training
95 posts since Jan 2012
Reputation Points: 10
Solved Threads: 0
> i got this code form the internet where it can delete a file.but when i tried to use it n my own java program it does not work anymore.it always returns 'Could not delete file'.
First thing, never have empty catch blocks in your code, ever, no matter what. Second, your code doesn't handle special conditions where failure to close a stream will result in other streams remaining unclosed thereby leaking file handles. Third, if the file "person.txt" is opened in Excel or some other program, it will allow you to read data from it but block deletion since the file is already open by some other application.
For first point, make sure you always log exceptions or at the very least print stack trace. For the second point, if you are using Java 7, you can write:
try (BufferedReader in = new BufferedReader(new FileReader(f)); PrintWriter out = new PrintWriter(tmp)) {
String s;
while ((s = in.readLine()) != null) {
out.print(s);
System.out.println(s);
}
}
And your streams will automatically be closed after the "try" block completes.
For third, make sure *no* other program is currently reading or has the given file open.
~s.o.s~
Failure as a human
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734