What is the best way to check file permissions in java

I need to check permissions to create files for a specific directory.

I tried:

try { AccessController.checkPermission(new FilePermission("directory_path", "write")); // Have permission } catch (SecurityException e) { // Doesn't have permission } 

... but this always throws a SecurityException (as I understand it, this does not check the basic permissions of fs, but some JVM parameters that must be explicitly configured).

Another possible way was to use something like this:

 File f = new File("directory_path"); if(f.canWrite()) { // Have permission } else { // Doesn't have permission } 

... but this returns true even if I cannot create the file in the specified directory (for example, I cannot create the file in "c: \" when starting my application as a user without administrator rights, but f.canWrite () returns true )

In the end, I did a hack similar to this:

 File f = new File("directory_path"); try { File.createTempFile("check", null, f).delete(); // Have permission } catch (IOException e) { // Doesn't have permission } 

... but this can only serve as a temporary solution, since I need to get such permissions for almost all folders on client fs.

Does anyone know how to properly obtain permissions to create REAL files without causing performance issues and hacks described above?

+4
source share
1 answer

The best way to check the availability / usability of any resource is to try to use it. In this case, new FileOutputStream(new File(dir, name)) . It will throw an IOException if the directory is not writable, or the file already exists and is not writable, etc. Etc. The operating system should already perform all these checks when executing this code: there is no point in trying to duplicate all this, and even if you get it 100% right, which is unlikely, you still enter a time window in which the previously β€œtrue” condition may become false due to asynchronous activity. You should still catch exceptions from the file creation and write code in the catch block to handle them: why write all this twice?

+1
source

All Articles