[Java] Check with Java/Kotlin that file cannot be written with UAC on Windows

2 minute read

TL;DR

If you support Windows, you should use java.nio.file.Files.isWritable.

Introduction

Unexpectedly I didn’t have any knowledge on the internet, so I took a memo for myself.

It is for Java/Kotlin’s file saving process, especially the process of letting the user select a directory and saving it.

As for the Java class, I actually did Kotlin, so the sample source conforms to it.

How to check write permission

There are two ways to check. Old way and relatively new way.

1.java.io.File.canWrite 2.java.nio.file.Files.isWritable

  1. is an instance method of the good old java.io.File class.
  2. is a static method of a relatively new class called java.nio.file.Files added in Java 1.7. In the first place, the java.nio.file.Files class handles only static methods.

It’s safer to use 2. for Windows. The details will be explained below.

java.io.File.canWrite

Again, this is an instance method.

Below sample.

sample.kt


val file = File("arbitrary file path")
val canWrite = file.canWrite() // true if writable

Very easy.

It only sees if the file is writable. In Linux, so-called Linux permissions, and in Windows, read-only attributes of file properties are targeted.

In other words, it is not possible to check whether the running Java process has the privilege for the OS. More specifically, it doesn’t support the permission check by UAC of Windows. **

Therefore, if it is a directory that can not be written without OS administrator privileges, such as directly under the C drive, even if canWrite is true, IOException will be thrown mercilessly when writing the file, which is a failure (Java process This is of course not the case if is running with administrator privileges)

java.nio.file.Files.isWritable

This is where this method comes into play. How to write is like this.

sample.kt


val file = File("arbitrary file path")
val canWrite = Files.isWritable(file.toPath()) // true if writable

This will check **including whether the Java process has write permission. Below is a quote from the Oracle JDK documentation. https://docs.oracle.com/javase/jp/8/docs/api/java/nio/file/Files.html#isWritable-java.nio.file.Path-

This method verifies that the file exists and that this Java virtual machine has the appropriate privileges to open the file for writing.

So, here you can check UAC as well. By the way, read and execute permissions can be checked in the same way with methods such as isReadable and isExecutable.

that’s all

As far as I’ve examined, UAC-related is the only article that was troubled by the installer of Vista era, and there was really no information other than Oracle reference. I wonder if it’s unexpectedly stuck here? Or are there few native application cases? ?

I hope it helps people who are stuck in the same event.