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

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.

This question is related to java file delete-file

The answer is


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.


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


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.


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.


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


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.


Problem is that check weather you have closed all the streams or not if opened close the streams and delete,rename..etc the file this is worked for me


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.


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

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.


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

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.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to file

Gradle - Move a folder from ABC to XYZ Difference between opening a file in binary vs text Angular: How to download a file from HttpClient? Python error message io.UnsupportedOperation: not readable java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Writing JSON object to a JSON file with fs.writeFileSync How to read/write files in .Net Core? How to write to a CSV line by line? Writing a dictionary to a text file? What are the pros and cons of parquet format compared to other formats?

Examples related to delete-file

Ansible: How to delete files and folders inside a directory? Can I delete data from the iOS DeviceSupport directory? Python3 project remove __pycache__ folders and .pyc files How do I delete files programmatically on Android? Delete files or folder recursively on Windows CMD How to delete a folder and all contents using a bat file in windows? How to delete a file or folder? How to remove a directory from git repository? Linux delete file with size 0 Java 'file.delete()' Is not Deleting Specified File