Search code examples
javawindowssecuritynionio2

In Java on WIndows how do I detect if file has 'Read Only' attribute


In Windows a file may not be writable because the user simply doesn't have permission to modify the file due to Access Control Lists permissions, or just because the read only attribute is set for the file.

My application is written in Java and either of these conditions could cause Files.isWritable(file) to fail, but how can I determine which condition caused the failure, specifically I just want to know if the read only attribute is set.

I note that there is a File.setReadOnly() method (as well as File.setWritable()), and I assume on Windows this would just set the attribute, but there doesn;t seem to be a File.isReadOnly() method.


Solution

  • I used this method to check if read only, (it uses custom method Platform .ifWindows() to only run on Windows, but you could use alternatives).

    private boolean isReadOnlyFile(Path file)
        {
            if(Platform.isWindows())
            {
                if (!file.toFile().canWrite())
                {
                    DosFileAttributes dosAttr;
                    try
                    {
                        dosAttr = Files.readAttributes(file, DosFileAttributes.class);
                        if(dosAttr.isReadOnly())
                        {
                            return true;
                        }
                    }
                    catch (IOException e)
                    {
    
                    }
                }
            }
            return false;
        }