How to check if a file can be deleted?

How can I verify that I can delete a file in Java?

For example, if the test.txt file test.txt opened in another program, I cannot delete it. And I must know this before the actual deletion, so I can not do this:

 if (!file.delete()) { ... } 

And srcFile.canWrite() doesn't work either.

+1
source share
4 answers

Open the file with write lock.

See here http://download.oracle.com/javase/6/docs/api/java/nio/channels/FileLock.html

 FileChannel channel = new RandomAccessFile("C:\\foo", "rw").getChannel(); // Try acquiring the lock without blocking. This method returns // null or throws an exception if the file is already locked. FileLock lock = channel.tryLock(); // ... // release it lock.release(); 
+3
source

In my 64-bit Windows 7 window using NTFS and Java 7, the only thing that worked reliably for me:

 boolean canDelete = file.renameTo(file) 

This is surprisingly simple and also works for folders that have an “open” or “locked” file “somewhere below”.

Other things I tried and created false positives: aquire FileLock, File # canWrite, File # setLastModified ("touch")

+4
source

On Unix, permission to write to the parent directory is required to delete the file.

On Windows, permissions can be much finer, but access to a directory entry will, in my opinion, catch most cases. In addition, you should try aqquire write lock on a file when under windows.

+3
source

You might want to explore FileLock . There is a FileChannel.tryLock () method that returns null if you cannot get the lock.

+1
source

Source: https://habr.com/ru/post/944965/


All Articles