Java file deletion error

I want to delete a file in java.It generate this result. How to delete a file. And what is the reason for this.

File l_file = new File(path);
System.out.println(l_file.exists()); //returns true
System.out.println(l_file.delete()); //returns false

      

Thank.

+3


source to share


6 answers


There are several reasons for a file failure. For example, if another process holds a descriptor in it or you do not have permission to delete this file. In both scenarios, you will be able to check the file for existence, but not delete it.



+1


source


There are many reasons why a file cannot be deleted. It is most likely that the file is open in another process, or that your process is running with less privilege than those required to delete the file.



0


source


The first reason is that there path

might be a directory

From the javadoc File#delete()

:

If this pathname denotes a directory, then the directory must be empty in order to be deleted.

Make sure the path is not an empty directory:

if (l_file.isDirectory()) {
   String[] files = l_file.list();
      if (files.length > 0) {
         System.out.println("The " + l_file.getPath() + " is not empty!");
      }
}

      


Another reason you can't uninstall path

is because you don't have permissions

Check your permissions:

if (l_file.canWrite())
   l_file.delete();

      

0


source


Perhaps you can try to check if this is a file (not a directory) of its permissions using the methods File

:

boolean isFile() // if it is a directory it must be empty
boolean canWrite()
boolean canRead()
boolean canExecute()

      

Also, as you can read in the Java API: "On some operating systems, it may not be possible to delete the file while it is open and in use by this Java virtual machine or other programs."

If you are on Linux, you can try lsof <file_name>

to find out which process opened this file.

0


source


You can also try FileChannel.lock()

or FileChannel.tryLock()

to see if you can get the lock before removing it.

0


source


There are two ways to solve this.

  1. Go to the file and change its properties to full control
  2. If you have exposed the PrintWriter or Scanner classes, you should close the class, especially the Scanner object, with .Close

    enter image description here
0


source







All Articles