51

This is currently what I have to delete the file but it's not working. I thought it may be permission problems or something but it wasn't. The file that I am testing with is empty and exists, so not sure why it doesn't delete it.

UserInput.prompt("Enter name of file to delete");
String name = UserInput.readString();
File file = new File("\\Files\\" + name + ".txt");
file.delete();

Any help would be GREATLY appreciated!

I now have:

File file = new File(catName + ".txt");
String path = file.getCanonicalPath();
File filePath = new File(path);
filePath.delete();

To try and find the correct path at run time so that if the program is transferred to a different computer it will still find the file.

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
Kimberley Lloyd
  • 537
  • 1
  • 5
  • 7

12 Answers12

79

The problem could also be due to any output streams that you have forgotten to close. In my case I was working with the file before the file being deleted. However at one place in the file operations, I had forgotten to close an output stream that I used to write to the file that was attempted to delete later.

user2926391
  • 831
  • 1
  • 6
  • 5
36

Be sure to find out your current working directory, and write your filepath relative to it.

This code:

File here = new File(".");
System.out.println(here.getAbsolutePath());

... will print out that directory.

Also, unrelated to your question, try to use File.separator to remain OS-independent. Backslashes work only on Windows.

Yassin Hajaj
  • 20,892
  • 9
  • 46
  • 83
Goran Jovic
  • 9,280
  • 3
  • 41
  • 74
  • 3
    And contrary to popular opinion, forward slashes *do* work on Windows. Just don't expect Windows to *return* paths with forward slashes. – meustrus Sep 05 '18 at 18:18
12

I got the same problem! then realized that my directory was not empty. I found the solution in another thread: not able to delete the directory through Java

/**
 * Force deletion of directory
 * @param path
 * @return
 */
static public boolean deleteDirectory(File path) {
    if (path.exists()) {
        File[] files = path.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                deleteDirectory(files[i]);
            } else {
                files[i].delete();
            }
        }
    }
    return (path.delete());
}
Community
  • 1
  • 1
Maha
  • 121
  • 1
  • 2
8

Try closing all the FileOutputStream/FileInputStream you've opened earlier in other methods ,then try deleting ,worked like a charm.

developerick
  • 3,164
  • 4
  • 35
  • 43
7

I suspect that the problem is that the path is incorrect. Try this:

UserInput.prompt("Enter name of file to delete");
String name = UserInput.readString();
File file = new File("\\Files\\" + name + ".txt");
if (file.exists()) {
    file.delete();
} else {
    System.err.println(
        "I cannot find '" + file + "' ('" + file.getAbsolutePath() + "')");
}
Stephen C
  • 669,072
  • 92
  • 771
  • 1,162
6

If you want to delete file first close all the connections and streams. after that delete the file.

Anurag Mishra
  • 61
  • 1
  • 3
3

In my case it was the close() that was not executing due to unhandled exception.

void method() throws Exception {
    FileInputStream fis = new FileInputStream(fileName);
    parse(fis);
    fis.close();
}

Assume exception is being thrown on the parse(), which is not handled in this method and therefore the file is not closed, down the road, the file is being deleted, and that delete statement fails, and do not delete.

So, instead I had the code like this, then it worked...

    try {
        parse(fis);
    }
    catch (Exception ex) {
        fis.close();
        throw ex;
    }

so basic Java, which sometimes we overlook.

Abdul Ahad
  • 51
  • 1
1

As other answers indicate, on Windows you cannot delete a file that is open. However one other thing that can stop a file from being deleted on Windows is if it is is mmap'd to a MappedByteBuffer (or DirectByteBuffer) -- if so, the file cannot be deleted until the byte buffer is garbage collected. There is some relatively safe code for forcibly closing (cleaning) a DirectByteBuffer before it is garbage collected here: https://github.com/classgraph/classgraph/blob/master/src/main/java/nonapi/io/github/classgraph/utils/FileUtils.java#L606 After cleaning the ByteBuffer, you can delete the file. However, make sure you never use the ByteBuffer again after cleaning it, or the JVM will crash.

Luke Hutchison
  • 7,084
  • 2
  • 37
  • 33
-1

I made the mistake of opening a BufferedReader like:

File f = new File("somefile.txt");
BufferedReader br = new BufferedReader(new FileReader(f));

...and of course I could not execute the f.delete() because I wrapped the FileReader instead of instantiating its own variable where I could explicitly close it. Duh...

Once I coded:

File f = new File("somefile.txt");
FileReader fread = new FileReader(f);
BufferedReader br = new BufferedReader(fread);

I could issue a br.close(); br=null; fread.close(); fread=null; and the f.delete() worked fine.

Wrigglenite
  • 121
  • 7
-1

In my case I was processing a set of jar files contained in a directory. After I processed them I tried to delete them from that directory, but they wouldn't delete. I was using JarFile to process them and the problem was that I forgot to close the JarFile when I was done.

Tom Rutchik
  • 633
  • 6
  • 9
-1

Since the directory is not empty, file.delete() returns false, always.

I used

file.deleteRecursively()

which is available in Kotlin and would delete the completely directly and return the boolean response just as file.delete() does.

Damanpreet Singh
  • 555
  • 8
  • 14
-2

If still not working you can call garbage collector to close the file and free up memory

System.gc();
if(new File("./__tmp.txt").delete()){
    System.out.println("OK");
}

Don't forget to close that file, if any previous opening using code snippet fio.close() I tested in Java 1.8, works well.

Prashant
  • 372
  • 1
  • 6
  • 17