How to check if I can delete a file?

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

For example, I must delete the C:/file.txt , but I can never delete C:/ or Computer , or My Documents , etc.

The solution described in a possible duplicate does not work for me.

+6
source share
2 answers

To delete a file, permission to write the parent file, that is, the directory in which the file is stored, is required. The directory in java is also represented by an instance of the java.io.File class, which has a canWrite() method.

So, to check if a file can be deleted, you should call file.getParent().canWrite() .

+10
source

In my 64-bit Windows 7 field using NTFS and Java 7 (Oracle JDK) the only thing that worked reliably for me was

 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've tried and created false positives: aquire FileLock, File # canWrite, File # setLastModified ("touch"), file.getParent (). canWrite ()

+3
source

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


All Articles