Reputation: 301
I have written code, which delete file from local file system. But it fails because someother thread is accessing that file.
Exception : the process cannot access the file because it is being used by another process. while deleting file java
Below code :
private class DeleteFileRecursively extends SimpleFileVisitor<Path> {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
if (file.toString().equals(
SECURE_PATH + File.separator + MMKEYSTORE)
|| file.toString().equals(
SECURE_PATH + File.separator + MMTRUSTSTORE)) {
Files.delete(file);
} else {
return FileVisitResult.SKIP_SIBLINGS;
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc)
throws IOException {
if (file.toString().equals(
SECURE_PATH + File.separator + MMKEYSTORE)
|| file.toString().equals(
SECURE_PATH + File.separator + MMTRUSTSTORE)) {
Files.delete(file);
} else {
return FileVisitResult.SKIP_SIBLINGS;
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path file, IOException exc)
throws IOException {
if (exc == null) {
if (file.toString().equals(
SECURE_PATH + File.separator + MMKEYSTORE)
|| file.toString().equals(
SECURE_PATH + File.separator + MMTRUSTSTORE)) {
Files.delete(file);
} else {
return FileVisitResult.SKIP_SIBLINGS;
}
return FileVisitResult.CONTINUE;
} else {
// directory iteration failed; propagate exception
throw exc;
}
}
Any idea about what i am missing, i wanted to delete file forcibly.
Upvotes: 1
Views: 484
Reputation: 5798
If you are running Windows then it will not be easy.
The OS just prohibits you to delete a File that is open. Just make sure you dont have the file open yourself is the only thing you can do.
if you want to delete it after you are done you can try File.deleteOnExit()
Upvotes: 2