Java 'file.delete()' Is not Deleting Specified File

JavaFileDelete File

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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.

Solution 3 - Java

I got the same problem! then realized that my directory was not empty. I found the solution in another thread: https://stackoverflow.com/questions/3987921/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());
}

Solution 4 - Java

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

Solution 5 - Java

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() + "')");
}

Solution 6 - Java

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

Solution 7 - Java

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.

Solution 8 - Java

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.

Solution 9 - Java

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.

Solution 10 - Java

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.

Solution 11 - Java

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.

Solution 12 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKimberley LloydView Question on Stackoverflow
Solution 1 - Javauser2926391View Answer on Stackoverflow
Solution 2 - JavaGoran JovicView Answer on Stackoverflow
Solution 3 - JavaMahaView Answer on Stackoverflow
Solution 4 - JavaAbhishek BhardwajView Answer on Stackoverflow
Solution 5 - JavaStephen CView Answer on Stackoverflow
Solution 6 - JavaAnurag MishraView Answer on Stackoverflow
Solution 7 - JavaAbdul AhadView Answer on Stackoverflow
Solution 8 - JavaLuke HutchisonView Answer on Stackoverflow
Solution 9 - JavaNoteBenderView Answer on Stackoverflow
Solution 10 - JavaTom RutchikView Answer on Stackoverflow
Solution 11 - JavaDamanpreet SinghView Answer on Stackoverflow
Solution 12 - JavaPrashantView Answer on Stackoverflow