Add permission to policy file in Java

This post about grant permission to write to a file using Security Manager.

Say, We have program to write in a file using FileWriter.

But, when you use -Djava.security.manager, the file gets permission denied. Why? Check out below.

Source Code:

public static void main(String args[]) {
 String version = System.getProperty("java.version");
 System.out.println("Print:" + version);
 try (FileWriter writer = new FileWriter("E:freelance workspaceJVM Securitywrite.txt")) {
 writer.write("hello world");
 } catch (Exception e) {
 System.out.println(e.toString());
 }
 }

From the above source code, I have complied the program and it is x path(say).

On cmd,I hit this java -Djava.security.manager -classpath . com.sample.test.TestSec.
But it showed the exception.

E:workspaceJVM Security>java -Djava.security.manager -classpath . com.sample.test.TestSec
Print:1.8.0_51
java.security.AccessControlException: access denied (“java.io.FilePermission” “E: workspaceJVM Securitywrite.txt” “write”)

How to get rid of the exception. I found a solution.
I used security manager. So I moved to jre->lib->security-> java.policy.
I just open the java.policy and added the line as below.
//after line number 23 in the java.policy file.
permission java.io.FilePermission “E:/workspace/JVM Security/write.txt”, “write”;

Then I came to cmd and hit this java -Djava.security.manager -classpath . com.sample.test.TestSec. It worked!!!. A file has been created with hello world in it.

Hope this post help you to use Security Manager in java.

Have any doubt comment below.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s