Java Code unable to delete file - java

My java code is unable to delete files on the the system hard drive.
Whenever file.delete() function is called, it returns false.
Any ideas, why that might be happening?

File.delete() can fail to delete a file for many reasons including:
you don't have correct permissions to delete the file
the file represents a directory and the directory is not empty
the file is locked by another process, (or even by the same process in say an unclosed FileOutputStream)
the file doesn't exist

File.delete() can return false if you are trying to delete a directory that is not empty, or the named file simply doesn't exist at the time of the call.
(if there is a permission issue, a SecurityException is thrown)

I had the same issue in my code and found that the culprit was actually an unclosed FileInputStream. After closing that FIS my file deleted without any problems. I hope this helps someone.

The usual reasons are insufficient permissions (although normally that would throw an exception), trying to delete a non-existant file or trying to delete a non-empty directory. Are you totally sure that you have permissions to delete the file you are trying to delete?

Some process might be reading/writing the file, so that it is locked. Or then your process does not have permissions to delete the file. If the file is a directory, all files inside it must be deleted first before the directory can be deleted. And finally there is the situation that the file does not exist, so the delete method will return false.

Windows? Use the Process Explorer to search for all processes which keep a handle (lock) on the file (or if this is a directory on any file inside of it).
On Linux, use fuser.

You might be trying to delete any file exists in C: Drive and on that you might not have the permissions to do so. Try to put it inside any other drive than C: and then run your code. Hope it works for you. :)

Make sure the file is not currently is use:
For example i was trying to delete a file using
f2.delete()
But it was unable to do as i was using BufferReader,FileWriter,BufferWriter etc.Close all those and then try.
buffer.close()
writer.close()

For those who are having trouble to delete file using file.delete(), your problem is that the file is still open.
Close buffer reader
Close File Writer
and most important CLOSE THE FILE before file.delete(), otherwise it will not delete.
Enjoy.

Related

Delete directory after moving files from it [Java]

I have a directory M:\SOURCE from which I have listed and moved it's contents until it is empty
After that, I want to go ahead and delete it, I have tried (yes I also made sure it was empty):
sourceFile being "M:\SOURCE"
sourceFile.delete()
Files.delete(sourceFile.toPath());
FileUtils.deleteQuietly(sourceFile);
FileUtils.deleteDirectory(sourceFile);
FileUtils.forceDelete(sourceFile)
There are no exceptions being thrown by any of the other methods and .delete() returns true
HOWEVER, the directory still exists and when trying to access the folder I get the following message from windows:
When running process explorer I can see that java is using that resource (This only happens when I try to delete the source, and bear in mind that trying to delete source directory is the last thing my program does)
And just to make me freak out even more, once I stop my java virtual machine, THEN the folder magically disappears. So Java did got the instruction right, it's just that is not willing to delete it until it's terminated
Running System.gc() before deleting the directory also didn't help, and my working directory is not the one I'm trying to delete
You can get this problem when using Files NIO calls which list or return a Stream of directory contents before deleting the directory.
Using try with resources on any Stream of Path returned by Files NIO can help prevent this issue:
try(Stream<Path> stream = Files.list(directory)) {
// do any work on contents - move / delete
}
// delete directory after closing stream above

Cannot write file to Documents folder

I'm trying to write to a file in Java, or create a new file if the file doesn't exist. (Using JDK 14). However, when I run the following code I get an IOException at the if statement condition that reads The system could not find the file specified if the file doesn't exist, and Access is denied if the file does.
File file = new File(filePath);
System.out.println(filePath); // C:\Users\username\Documents\test.txt
if (file.createNewFile()) {
System.out.println("File successfully created");
} else {
System.out.println("File already exists");
}
The code works when I attempt to save it to the desktop folder and saves the file successfully, but for whatever reason isn't allowed to touch Documents.
The user I'm running IntelliJ as has full access to all files on the computer, and running the IDE as administrator did not fix the problem. However, I can save to the user folder and the desktop. It is only Documents or child directories of it that I can't save to.
There are a few similar questions on the site such as this one, however the cause is not the same as in my case this is a permissions issue, and not an issue of a missing directory.
I've just hit this same issue. It seems that JFileChooser() on some Windows 10 installations doesn't tell the os that the user has selected a folder and as such Sandboxing, Malware Control, Access control blocks access to create a file even though the user had full access (permission checks are OK but file write fails with IOException 13 or Access Denied). However FileDialog() DOES work where JFileChooser fails...
Heres what I would do to try to debug this:
Should you be trying to save to 'My Documents' as opposed to 'Documents'?
Try to save the file to C:\Users\username\test.txt (I suspect that will work)
Try to save the file to C:\Users\username\My Documents\test.txt
If you really do want to save it to 'Documents' make sure the 'Documents' director exists.
If thats the case, open the properties on Documents under the security tab select Everyone under 'Group our user names' and 'Full control' under permissions. that will open it wide up and should allow file creation. you might want to take note of what the settings where so you can put them back as setting a directory to wide open permissions can be 'problematic'. try running the program again.
1
if you want write data to file just user any Writer For example:
FileWriter writer = new FileWriter(yourFile);
You can use stream filtering for faster action.
Show more your code. You've just showed condition for existing file.
2
if you want create file in Documents folder, get a path, then make a:
File file = new File(documentPath);
while(!file.exists())
file.createNewFile();
//condition for file existing...`
If I don't help, comment below, just I can't understand your question :). Good Luck

Merge multiple PDF (from same folder) document with Java PdfBox [duplicate]

I am trying to read the files inside a folder, but when I run the program it throws this exception. I tried with some other folders also. It throws the same exception.
Exception in thread "main" java.io.FileNotFoundException: C:\backup (Access is denied)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
You cannot open and read a directory, use the isFile() and isDirectory() methods to distinguish between files and folders. You can get the contents of folders using the list() and listFiles() methods (for filenames and Files respectively) you can also specify a filter that selects a subset of files listed.
check the rsp's reply
check that you have permissions to read the file
check whether the file is not locked by other application. It is relevant mostly if you are on windows. for example I think that you can get the exception if you are trying to read the file while it is opened in notepad
Also, in some cases is important to check the target folder permissions. To give write permission for the user might be the solution. That worked for me.
Here's a gotcha that I just discovered - perhaps it might help someone else. If using windows the classes folder must not have encryption enabled! Tomcat doesn't seem to like that. Right click on the classes folder, select "Properties" and then click the "Advanced..." button. Make sure the "Encrypt contents to secure data" checkbox is cleared. Restart Tomcat.
It worked for me so here's hoping it helps someone else, too.
Check the file path properly, usually we mention the location and forget to specify the file name or the exact position where it belongs to.
This solution worked:
My JDK is installed in one directory(C drive) and
my java program as well as other files are in another directory(D drive).
Here's the solution from another Stack Overflow question

File renameTo & File.delete

I have been writing a program for batch system using quartz and i find a problem,
if(!file.renameTo(new File(PATH_FILE_PROCESSED+file.getName())))System.out.println("Cannot Move File :"+file.getAbsolutePath());
else{
if(!file.delete())System.out.println("Cannot Delete File :"+file.getAbsolutePath());
}
i want to move file from one directory to another directory but i can't delete the file in the same process, from my analysis i think the file haven't finished copying then running the file.delete();
my question is, is there a way to wait until the file finished copying then run the file.delete?
thanks
Renaming is almost instant as it doesn't copy the file, it just moves which directory it appears in (unless you are moving between filesystems)
On windows, you can't rename or delete if you have the file open somewhere. Make sure you have close()ed it properly.
i think i already found the problem, the problem is when i insert the the file inside zip some other code already insert the data so it create duplicate in database and it create an error like this. so thanks for answering the question

File.exists() returns false when file exists

I've encountered a bug I can't seem to find any logic behind. I have this File object, which is created like this:
File file = new File("utilities/data/someTextFile.txt");
I then do file.exists(), and it returns false (!?). If the file is not found, I'm logging f.getAbsolutePath() to a file. When I look at the path, it seems OK. I can copy-paste the complete path into the "Run"-window in Windows and the file opens fine.
The file exists at all times and is not deleted nor changed during the running of my application. It is located at the local machine.
This only seems to occur in certain situations. I can reproduce the fault at any time, but I'm sure the path of the file object is not changed by the actions I make to reproduce the fault.
What can cause file.exists() to return false? Does this have something to do with permissions or file locks, etc.?
I am seeing the following situation on Windows 7:
file.exists() == false
file.getAbsoluteFile().exists() == true
The file in question is "var\log", the absolute path does refer to an existing file that is in a normal subdirectory (not a virtual store). This is seen from the IDE.
It seems like there is a difference on how the path is specified in Java.
For example, if the file path is specified as file:/C:/DEV/test.txt then
File f = new File(filename);
f.exists();
will return false. The path might work in the explorer or in the browser, but it is a URL and not absolute file path.
But on the other hand if the file path is specified as C:/DEV/test.txt then
File f = new File(filename);
f.exists();
will return true because the path is not a URL, but it is a absolute path.
With Spring Framework that is exactly what ResourceUtils.getFile(filename) does - where name can be either a URL or the absolute file path.
If the process does not have permissions to tell whether a file exists it will return false. It may be possible to open a file, but not tell by normal methods if it exists.
The above answers didn't help out in my case. As stated above, I had:
file.exists() => false
file.getAbsoluteFile().exists => true
The root cause for this was that the Windows 7 machine owner had modified the registry for CMD so that it would autorun a command to launch in a specific directory to work with Python. This modification crippled the Java 1.6 code which apparently uses CMD on Windows for certain file operations, such as exists(). Eliminating the autorun from the registry solved the issue.
When ["Hide extensions for known file types."] is checked windows open "t.txt.txt" when type "t.txt" in [explorer]/[run windows] but programmatically not.
Obviously there are a number of possible causes and the previous answers document them well, but here's how I solved this for in one particular case:
A student of mine had this problem and I nearly tore my hair out trying to figure it out. It turned out that the file didn't exist, even though it looked like it did. The problem was that Windows 7 was configured to "Hide file extensions for known file types." This means that if file appears to have the name "data.txt" its actual filename is "data.txt.txt".
Hope this helps others save themselves some hair.
If you don't want to deal with getAbsoluteFile() calls each time you have to call a method, you better create your file instance already with an absolute path. This should do the trick:
File file = new File("utilities/data/someTextFile.txt").getAbsoluteFile();
I suggest to surround it with a try-catch block, BTW.
The new File command just creates an instance of a file using the given path name. It doesn't actually create a file on the hard drive.
If you say
File file = new File ("path");
file.exists()
This can return true only if there was an existing file with the same path. If you intended to check for the same file declared in the first line, you may need to use it this way.
File file = new File ("path");
file.createNewFile();
file.exists();
Now this will return true.
To generalize the issue the problem arises while converting URL/URI to local paths.
Example: URL url = file:/D:/code%20repo%20sample/sample.txt
// To remove url reference
String localPath = url.getPath();
> /D:/code%20repo%20sample/sample.txt
// Decoding reserved characters in url from hexadecimal to character
URLDecoder.decode(localPath, StandardCharsets.UTF_8.toString());
> /D:/code repo sample/sample.txt
Hope this helps.
In my case
file save in
filepath = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/VRSI/Audio/"+encrypted_filename+".mp3";
It is stored in in
/storage/emulated/0/VRSI/Audio/82B0999F16251F0DFE849F380D6AAEEA.mp3
it when when I get the file path is
/storage/emulated/0/Android/data/com.numerotec.vrsi/files/VRSI/Audio/AF7DC6C0C0B3EF3529EC70DAEF2324E0.mp3
So I replace the the string "Android/data/com.numerotec.vrsi/files/" as empty
after that
if (file.getAbsoluteFile().exists())
{
// write your code
}
is working fine
Good responses everyone. I've found this seems to be a problem with Java accessing the root C: directory on Windows. Any other directory should be fine, but for some reason, specifically mentioning C:\ or C: or C:/ might give an error. I have resolved this very similar problem by trapping mention to new File("C:"); and replacing it with new File(System.getProperty("file.separator")); or you should be able to hard code "\" instead of saying "c:" as your file directory and it might work out. Not elegant, but got the job done for me on this project.
I hope it helps. Might not be the right solution, but at least it worked for me. I'm on JRE 1.6, Win 7. Cheers!
Respectfully,
#Carpenter1010
If the situations where it fails involves running it as another user, and you're on Windows Vista/Windows 7, it could be caused by VirtualStore, the mechanism where Windows let an unprivileged user "write" places it normally cannot. The changes are however stored in "%USERPROFILE%\AppData\Local\VirtualStore\" which are private to each user account.
When nothing from above worked for me, I tried
filePath = filePath.trim();
This will clean your string from any unwanted charachter
FWIW, there is another place that this happens.
File("") is the name of the current directory. File("").exists() will usually return false. The File(("").getAbsoluteFile().exists() trick works and will return true (presuming the current directory exists...)
My suggestion is to attempt to read the file.
By doing so, i was able to get this error, that showed me that some weird characters had been prepended to my path.
java.nio.file.NoSuchFileException: ‪/home/rasp2/MyProjects/mapping.txt
In my IDE this was the path i was seeing:
Path path = Paths.get("/home/rasp2/MyProjects/mapping.txt");
So... i really don't know how, but these characters ‪ got into the way.
By deleting the path in the IDE and recreating it, i was able to get Files.exists(path) == true
I lately came across this same issue. What l did was to uninstall Netbeans, deleted netbeans folder from C drive, program files, update, programData, virtually everywhere. Then reinstall. Is now working fine.
Don't forget to backup up netbeans project folder before taken the actions above.
Hope it helps.
With some IDE(may be) and or with some OS(ex: window), by default they don't have write access on files. So if you try to do file.exists() it will show you false. in order to fix this, do like below
if your ref variable for File is f, example: File f = new File("path");
so in order to make it work , select f by mouse and then go to Search menu > Write access>Workspace. Hopefully it will work.
I think you should use backslash instead , like this:
File file = new File("C:\\User\\utilities\\data\\someTextFile.txt");
(two backslashes , not a typo )
Should solve the problem :)

Categories