We help IT Professionals succeed at work.

Delete a file in Java

abuyusuf
abuyusuf used Ask the Experts™
on
Hi

I am reading a file in Java using BufferedReader and writing it to a different file using BufferedWriter and FileWriter - the reason I used this is because after a lot of work I found out that 'rename' function in File wasn't working as expected. Well I am able to rewrite the file to a different name now - but the issue is that I can't delete the existing file. Anu suggestions

Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Awarded 2011
Awarded 2011

Commented:
This  worked for me - provided you have neceessary permissions:

File f = new File("filename.txt");
f.delete();

Awarded 2011
Awarded 2011

Commented:

I alaso did that and it worked for me fine, if file1.txt exists and file2.txt does not:

File f0 = new File("file1.txt");
File f1 = new File("file2.txt");

f0.renameTo(f1);

Awarded 2011
Awarded 2011

Commented:
I just tried this and it renamed for me:

     try {
File f0 = new File("file1.txt");
File f1 = new File("file2.txt");

f0.renameTo(f1);
      }catch(Exception ex){
          ex.printStackTrace();
      }

Open in new window

Awarded 2011
Awarded 2011

Commented:
It is important that you close all readers and writers before you try to delete or to remove any files involved.

Author

Commented:
Doesn't work for me that's why I'm asking. Thanks
Awarded 2011
Awarded 2011

Commented:
On what OS you are running?
Did you try to reanme it manually with the same privileges?
Awarded 2011
Awarded 2011

Commented:
Check what boolean value return delete() and renameTo() methods.
If they faile they should return false value
Awarded 2011
Awarded 2011

Commented:


Read this about deleteing file in java after reading with BufferedReader (see acceptefd answer and other stuff there):
http://stackoverflow.com/questions/991489/i-cant-delete-a-file-in-java
Top Expert 2016

Commented:
>>I found out that 'rename' function in File wasn't working as expected.

Can you post the code you tried?

Author

Commented:
For some reason this only happens on Windows XP with JDK 1.6 - it works fine on Windows 7
Awarded 2011
Awarded 2011
Commented:
Try different options - try not to open and not read or write any of the files - just like in my short snippet above - take
some new names an create one new file from outside java and see if you can just rename it without manipulating with it in any way before.
(see the talks from stackoverflow that it was connected to previous buffered reader or something)

Another test - check if it happens on different drives.

I also use XP and Java 1.6 and can rename without problems