1

In windows there is a known bug where a folder can have read only property enable.

I have a file that have this property enabled and I need to delete it. But File.delete delete this folder whereas Files.delete can't.

Here a sample to reproduce my issue. I am in the case where the folder i want to delete is empty

    public static void main(String[] args) throws IOException {

        File tmpDir = new File(System.getProperty("java.io.tmpdir"));
        File someDir = new File(tmpDir, "someDir");

        Files.setAttribute(someDir.toPath(), "dos:readonly", true);

        //        someDir.delete(); //ok
        Files.delete(someDir.toPath()); //fail

}

Files.delete seems more appropriated according to this post but in my case it doesn't work.

In this case I can set the property back to false and I am fine but what is the right choice to do between those two method ? Should I try to use both if one failed ?

user43968
  • 2,049
  • 20
  • 37
  • Do you have files in this directory ? – davidxxx Jul 13 '18 at 14:05
  • No file in this directory (good point, I update the question) . The code posted here is sufficient to reproduce the problem – user43968 Jul 13 '18 at 14:11
  • 2
    Ok ! So it seems that `Files.delete()` respects the readonly property despite the Window bug while `File.delete()` preserves the Windows bug. Conceptually it it wrong that a read only directory may be deleted. So I would try to change the file property. Don't you have the permission at runtime to disable the readonly property on this dir such as : `Files.setAttribute(someDir.toPath(), "dos:readonly", false);` ? – davidxxx Jul 13 '18 at 14:18
  • Yes in my case no problem to set the property back to false (may be i am moving the problem to set attribut now). But what if I found the opposite scenario ? What's the best way to deal with this problem ? Should I use Files.delete with the property to false or simply use File.delete and no worries..... – user43968 Jul 13 '18 at 14:22
  • Personally, I don't like any of these ways : old and flawed API that respects the Windows behavior and a recent and better designed API but that is not conform to the underlying OS. But to get a relevant error message if the operation fails I think that I would stick to `Files.delete()`. Now in cases of the file attribute cannot be changed in "not readonly", using `File.delete()` as workaround is probably the way. – davidxxx Jul 13 '18 at 14:32

0 Answers0