2

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

For example, if a file test.txt is opened in another program I can't delete it. And I have to know it before actual deletion, so I can't do this:

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

And srcFile.canWrite() is not working either.

VextoR
  • 5,087
  • 22
  • 74
  • 109
  • what happens when you use try/catch blocks? – posdef Feb 22 '11 at 12:25
  • Look at http://stackoverflow.com/questions/991489/i-cant-delete-a-file-in-java – rayyildiz Feb 22 '11 at 12:26
  • Thanks, but questions not about deleting but knowing that file in use by another proccess now, so it actually should not be deleted.. – VextoR Feb 22 '11 at 12:30
  • Generally speaking that's a question that you won't get a good answer to in most OS: there may be many factors that determine if you can delete a file or not and the only sure-fire way to check is to try it. – Joachim Sauer Feb 22 '11 at 12:49

4 Answers4

5

On my Windows 7 64 bit box using NTFS and Java 7, the only thing which worked for me reliably is

boolean canDelete = file.renameTo(file)

This is surprisingly simple and works also for folders, which have "somewhere below" an "open" or "locked" file.

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

Peti
  • 1,670
  • 1
  • 20
  • 25
3

Open the file with a 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();
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
servermanfail
  • 2,532
  • 20
  • 21
  • 4
    That's only a partial solution: it's possible to get write access to a file and still not be allowed to delete it. – Joachim Sauer Feb 22 '11 at 12:36
  • 1
    thanks, it works. But I had to call channel.close() after lock.release() to be able delete a file, because file was locked by FileChannel. – VextoR Feb 22 '11 at 13:16
  • 1
    I found situation where that's not working - as Joachim Sauer said. So do you know any final solution to this ? – greendraco Feb 22 '13 at 10:06
  • actually I found this working for me: http://stackoverflow.com/a/13048956/1829381 – greendraco Feb 22 '13 at 10:13
3

Under Unix, you need write permission to the parent directory in order to delete a file.

Under Windows, permissions can be a lot more fine-grained, but write-access to the directory would catch most cases there as well, I believe. In addidtion, you should try and aqquire a write-lock on the file when under windows.

gnud
  • 77,584
  • 5
  • 64
  • 78
1

You might want to look into FileLock. There is a FileChannel.tryLock() method that will return null if you cannot obtain a lock.

Bala R
  • 107,317
  • 23
  • 199
  • 210