java file.delete() returns false but file.exists() returns true

落爺英雄遲暮 提交于 2019-11-27 04:45:14

问题


When I am trying to delete a file which is present in tomcat server conf/Catalina/localhost from java code then file.delete() always returns false. But if I am checking the file by file.exists() function it returns true. I am not getting any exception. Please help us why this is happening. What is the solution for this?


回答1:


When I am trying to delete a file which is present in tomcat server conf/Catalina/localhost from java code then file.delete() always returns false. But if i am checking the file by file.exists() function it returns true.

Most likely you do not have permission for deleting file(s) on Server. Check your permissions.

f.delete() returns false it means that it wasn't / could not be deleted and f.exists() returns true so file exists but cannot be deleted.




回答2:


There are any number of reasons why a file cannot be deleted; it may not exist, it may be a non-empty directory, you may not have closed all resources using it, and your program may not have permission to do so, to name a few.

Unfortunately the File.delete() method provides very little information as to why; it's pretty much up to you to poke around and figure it out. But there's good news; you don't want to use File in the first place.

Java 7 introduced the new java.nio.file package which is a much more robust file access API. It provides the concept of an abstract Path and separates concrete operations into the Files class, in particular it provides Files.delete() which is documented to raise clear exceptions describing the reasons deletion might fail.

Use Path and Files; you'll be glad you did.




回答3:


You must close the stream before deleting it.

e.g -

fileInputStream.close();
file.delete();



回答4:


If the directory is non-empty then File.delete() method will return false without throwing an Error.

You must cleanup the directory before deleting it.




回答5:


It means that file is existing, but your java process dont have the permission to delete that.That is why delete function is returning false

Returns: true if and only if the file or directory is successfully deleted; false otherwise




回答6:


before deleting the file your should close all the file reading and writing connection after 100% file will be deleted for example buffedreader.close() outputstream.close()



来源:https://stackoverflow.com/questions/15336565/java-file-delete-returns-false-but-file-exists-returns-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!