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, 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) {

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

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

E:workspaceJVM Security>java -classpath . com.sample.test.TestSec
Print:1.8.0_51 access denied (“” “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 “E:/workspace/JVM Security/write.txt”, “write”;

Then I came to cmd and hit this java -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.


Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.