File permission check in java

How to check file permissions in Java (OS independently)

Second, when we check file permissions on remote drives, it’s usually not enough just setting it in the Windows Explorer( Property. — Solution 3: First of all, Java trust local files and untrust remote files by default and by design.

How to check file permissions in Java (OS independently)

I have the following snippet of code:

public class ExampleClass < public static void main(String[] args) throws FileNotFoundException < String filePath = args[0]; File file = new File(filePath); if (!file.exists()) throw new FileNotFoundException(); if (file.canWrite()) System.out.println(file.getAbsolutePath() + ": CAN WRITE. "); else System.out.println(file.getAbsolutePath() + ": CANNOT WRITE. "); if (file.canRead()) System.out.println(file.getAbsolutePath() + ": CAN READ. "); else System.out.println(file.getAbsolutePath() + ": CANNOT READ. "); if (file.canExecute()) System.out.println(file.getAbsolutePath() + ": CAN EXECUTE. "); else System.out.println(file.getAbsolutePath() + ": CANNOT EXECUTE. "); >> 

It works in Linux OS, but the problem is that it doesn’t work in windows7. So the question is: Does anybody know a method to check privileges to a file in Java OS INDEPENDENTLY?

This might be caused by something (for instance an anti-virus product) «mediating» file access in an inconsistent way.

Certainly, it is hard to believe that the Java File.canXxxx() methods are generally broken on any flavour of Windows.

UPDATE — I take that back. Read this Sun bug report . and weep. The short answer is that it is a Windows bug, and Sun decided not to work around it. (But the new Java 7 APIs do work . )

Читайте также:  Java working with database

FWIW, I maintain that it is BAD PRACTICE to try to check file access permissions like that. It is better to simply attempt to use the file, and catch the exceptions if / when they occur. See https://stackoverflow.com/a/6093037/139985 for my reasoning. (And now we have another reason . )

I have done some tests on the NIO APIs (from Java 7) and they seem to work perfectly.

import java.io.FileNotFoundException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class PermissionCheck < public static void main(String[] args) throws FileNotFoundException < String filePath = args[0]; Path p = Paths.get(filePath); if (Files.notExists(p)) throw new FileNotFoundException(); if (Files.isWritable(p)) . if (Files.isReadable(p)) . if (Files.isExecutable(p)) . >> 

First of all, Java trust local files and untrust remote files by default and by design. So when testing, be aware of that what you can do in your computer at home, may be impossible in some remote drive of your company’s server.

Second, when we check file permissions on remote drives, it’s usually not enough just setting it in the Windows Explorer( Property. — Read only / Hide / Archive , etc. ). For example, my organization have other mechinisms to control both local and remote file permission, and even being Administrator of my PC cannot guarantee everything. Even if manually/programmatically you can change the permission of a file, if some other applications/group policy/etc forbids you to do so, the change may fail. (For example, setReadable() returns false , suggesting that it’s not possible)For example, I can execute a txt file in a remote directory, meaning open it, but a bat file in the same directory is not executable, actually, in my case, I am required to ask my admin to gain more authority when I want to create a bat file. I think it might be that bat extension are forbidden. Because as user in some user group in Windows, your action and JVM run by you are limited by higher rules than JVM itself. Correct me if I am wrong.

However, even if you might not be able to set the permisson of a file, now you can read them correctly in Java 7. Obviously after the bug report, Java guys had done something to fix the most of it. I am using jdk 1.7.0_19 , and to test, I have done the following:

  1. Set the property of a remote file, in Windows Explorer, to Read Only and Hidden .
  2. Read it from Java, with code below (from the link of Stephen C and modified to see setXxxxx() methods can work).
import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class FilePermissionTester < public static void main( String[] args ) throws IOException < File file = new File("Y:\\some\\remote\\drive\\directoy\\xxxxx.txt"); System.out.println( "exists:" + file.exists() ); System.out.println( "is file:" + file.isFile() ); System.out.println( "can read:" + file.canRead() ); System.out.println( "can execute:" + file.canExecute() ); System.out.println( "can write:" + file.canWrite() ); System.out.println( "is hidden:" + file.isHidden() ); System.out.println("change it to be unreadable, and it works? " + file.setReadable(false)); System.out.println( "can read:" + file.canRead() ); System.out.println("change it to be writable, and it works? " + file.setWritable(true)); System.out.println( "can write:" + file.canWrite() ); FileInputStream fileInputStream = new FileInputStream(file); fileInputStream.read(); fileInputStream.close(); >> 
exists:true is file:true can read:true can execute:true can write:false is hidden:true change it to be unreadable, and it works? false can read:true change it to be writable, and it works? true can write:true 

And now I can read this file, edit it and save it. Before changing the permission I was asked to Save As.. when saving.

Note that the file is readable, and setReadable(false) returns false , and the file is still readble. JavaDoc says here that setReadable() return false when user haven’t permission to change the access premission, or when readable is already false , and the underlying system doesn’t have implementation for this. Debugging into Java API doesn’t provide much info, because the implementation are marked native and cannot see more. But I have the permission to change the writability, so that’s something I don’t understand.

But also note that there are more attributes out there that are not supported by java.util.File , like setHidden() . Maybe you can check other pacakges in java.security , like AccessController?

Java — Checking for write access in a directory before, I finally settled with the following solution. //User places the input file in a directory and selects it from the GUI //All output files will be created in the directory that contains the input file File fileBrowse = chooser.getSelectedFile (); //chooser is a JFileChooser File sample = new File (fileBrowse.getParent (),»empty.txt»); try

How to check write permissions of a directory in java?

I would like a code snippet that checks whether a directory has read/write permissions and do something if it does, and does something else if it doesnt. I tried an example shown here:

try < AccessController.checkPermission(new FilePermission("/tmp/*", "read,write")); System.out.println("Good"); // Has permission >catch (SecurityException e) < // Does not have permission System.out.println("Bad"); >

The problem is the exception is always triggered, so it always ends up printing «Bad» regardless of whether the directory has write permissions or not. (I chmod the directories to 777 or 000 to test).

Is there an alternative or some way to accomplish what I need?

In Java 7 i do it like this:

if you just want to check if you can write:

File f = new File("path"); if(f.canWrite()) < // write access >else < // no write access >

for checking read access, there is a function canRead()

You should use the path of the directory alone ( «/tmp» ) to query the permissions of a directory:

AccessController.checkPermission(new FilePermission("/tmp", "read,write")); 

With «/tmp/*» you query the permissions of all files inside the /tmp directory.

Java has its own permission model revolving around the use of an AccessController and Permission classes. The permissions are granted to a code source (the location from where the classes are loaded), and in some/most cases these permissions are different from any underlying permissions required to access the desired resource.

For instance, although you may have granted all users to read and write to the /tmp directory, this isn’t sufficient for the AccessController to grant your code the necessary permission. You’ll also need to add a rule in the policy file used (by the AccessController) to read and write files from the /tmp directory. The rule to be created will be equivalent to the following:

How to check if a file is readable, writable, or, executable, The isExecutable () method − This method accepts an object of the Path class and verifies whether the file represented by the given path exists in the system and JVM has permissions to execute it. If so, it returns true else it returns false. The Files class

How can i get the file permission of a directory with java

i try to check the permission granted to a directory in linux, i mean i have a directory with permission 755

berty@berty-laptop:~$ ls -l / |grep directory drwxr-xr-x 3 root root 4096 2011-01-10 12:33 directory 

how can i read that permission with java? I’ve tried using FilePermission but though i have a directory with all the permissions (777) the FilePermission class always returns an exception

java.security.AccessControlException: Access denied (java.io.FilePermission /home/directory read) at java.security.AccessController.checkPermission(AccessController.java:103) at com.snippets.Check4DirectoryPermission.checker(Check4DirectoryPermission.java:50) at com.snippets.Check4DirectoryPermission.main(Check4DirectoryPermission.java:70) 

is there another way to do this?

java.io.File.canRead() , where the file instance is the one representing the dir

Returns: true if and only if the file specified by this abstract pathname exists and can be read by the application; false otherwise

I think you made a mistake: The ls command shows the existence of /directory , but the Java code complaints about /home/directory — which does not exist unless you have a user called directory .

From your stack trace, I assume that you are creating a FilePermission object yourself and hand it over to AccessController.checkPermission(). This is not how it is used — the FilePermission class does NOT represent the filesystem permissions and does NOT check them. It is used by Java’s SecurityManager only, e.g. it looks whether the policy file contains rules that allow the application to access the file. Whether the local file system supports permissions or not is not its concern.

As Bozho suggest, you create a java.io.File() object and use the canXXX() methods to check whether you can access the folder or file.

If you need more detailed information about filesystem-level permissions on a file, you need to wait for Java 7. See the Java NIO.2 Tutorial especially the java.nio.file.attribute package.

File Permissions in Java, Java provides a number of method calls to check and change the permission of a file, such as a read-only file can be changed to have permissions to write. File permissions are required to be changed when the user wants to restrict the operations permissible on a file.

Источник

File permission check in java

  • Introduction to Java
  • The complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works – JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?
  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods
  • Access Modifiers in Java
  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java
  • Inheritance in Java
  • Abstraction in Java
  • Encapsulation in Java
  • Polymorphism in Java
  • Interfaces in Java
  • ‘this’ reference in Java

Источник

Class FilePermission

This class represents access to a file or directory. A FilePermission consists of a pathname and a set of actions valid for that pathname.

Pathname is the pathname of the file or directory granted the specified actions. A pathname that ends in «/*» (where «/» is the file separator character, File.separatorChar ) indicates all the files and directories contained in that directory. A pathname that ends with «/-» indicates (recursively) all files and subdirectories contained in that directory. Such a pathname is called a wildcard pathname. Otherwise, it’s a simple pathname.

A pathname consisting of the special token «>» matches any file.

Note: A pathname consisting of a single «*» indicates all the files in the current directory, while a pathname consisting of a single «-» indicates all the files in the current directory and (recursively) all files and subdirectories contained in the current directory.

The actions to be granted are passed to the constructor in a string containing a list of one or more comma-separated keywords. The possible keywords are «read», «write», «execute», «delete», and «readlink». Their meaning is defined as follows: read read permission write write permission execute execute permission. Allows Runtime.exec to be called. Corresponds to SecurityManager.checkExec . delete delete permission. Allows File.delete to be called. Corresponds to SecurityManager.checkDelete . readlink read link permission. Allows the target of a symbolic link to be read by invoking the readSymbolicLink method.

The actions string is converted to lowercase before processing.

Be careful when granting FilePermissions. Think about the implications of granting read and especially write access to various files and directories. The «>» permission with write action is especially dangerous. This grants permission to write to the entire file system. One thing this effectively allows is replacement of the system binary, including the JVM runtime environment.

Please note: Code can always read a file from the same directory it’s in (or a subdirectory of that directory); it does not need explicit permission to do so.

Источник

Оцените статью