If you want to support Windows, you should use
I didn't know anything about the internet, so I wrote a memo for myself.
The target is the process of saving a file in Java / Kotlin, especially the process of letting the user select a directory and saving it.
I'm talking about Java classes, but since I actually did Kotlin, the sample source follows that.
There are two ways to check. The old way and the relatively new way.
is an instance method of the good old
is a static method of a relatively new class added in Java 1.7 called
In the first place, the
java.nio.file.Files class deals only with static methods.
It is said that it is safer to use 2. for Windows. I will explain the details from now on.
java.io.File.canWrite Again, this is an instance method.
Below is a sample.
val file = File("Arbitrary file path") val canWrite = file.canWrite() //True if writable
This only looks to see if the file has the writable attribute. For Linux, so-called Linux permissions, and for Windows, the read-only attribute of file properties.
In other words, it is not possible to check whether the running Java process has authority to the OS. More specifically, ** It doesn't support Windows UAC permission check. ** **
Therefore, if the directory cannot 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). Of course, this is not the case if is running with administrator privileges)
java.nio.file.Files.isWritable That's where this method comes in. How to write is like this.
val file = File("Arbitrary file path") val canWrite = Files.isWritable(file.toPath()) //True if writable
This will check if the Java process has writable permissions ** as well. The following 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 ** this Java virtual machine has the appropriate privileges to allow the file to be opened for writing **.
So, here you can check including UAC.
By the way, read permission and execute permission can be checked in the same way with methods such as ʻisReadable
As far as I checked, there were only articles related to UAC that were troubled by the installer in the Vista era, and there was really no information other than the Oracle reference. Isn't it unexpectedly stuck here? Or are there few examples of native apps in the first place? ??
I hope it helps people who are stuck with the same event.