2

This code creates a .txt in the folder directory (it works) but when comes the time to delete the whole directory or the .txt file using delete() method, nothing happens. The delete() method works only when I replace the .txt file with an ordinary folder

import java.io.*;

public class Filemkdir {
        public static void main(String[] args) throws Exception {
                File f = new File("C:/Temp/Java/secret.txt");


                FileWriter fSecret = new FileWriter(f);
                f.mkdir();

                f.delete();
        }
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
AchillesVan
  • 4,156
  • 3
  • 35
  • 47
  • Similar discussion you can check it [link](http://stackoverflow.com/questions/991489/i-cant-delete-a-file-in-java) – erhun Jan 23 '13 at 20:06

4 Answers4

5

On Windows you can't delete an open file. Close the FileWriter first.

Also, the

f.mkdir();

seems completely pointless.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
2

Maybe the fSecret (FileWriter) needs to be closed first. Otherwise the file is "in use"

fSecret.close(); 
Niels
  • 48,601
  • 4
  • 62
  • 81
1

You would basically need to close the writer object before deleting the file

Anugoonj
  • 575
  • 3
  • 9
0

File delete work on file, if you are trying to delete directory you first need to delete all files inside id.

with your code you are giving path for file, but you are creating directory after that.