25
final File parentDir = new File("S:\\PDSPopulatingProgram");
parentDir.mkdir();
final String hash = "popupateData";
final String fileName = hash + ".txt";
final File file = new File(parentDir, fileName);
file.createNewFile(); // Creates file PDSPopulatingProgram/popupateData.txt

I am trying to create a file in a folder but I am getting exception as

java.security.AccessControlException: Access denied

I am working in windows environment. I can create a folder from the Windows Explorer, but not from the Java Code.

How can I resolve this issue?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
arsenal
  • 23,366
  • 85
  • 225
  • 331

3 Answers3

27

Within your <jre location>\lib\security\java.policy try adding:

grant { permission java.security.AllPermission; };

And see if it allows you. If so, you will have to add more granular permissions.

See:

Java 8 Documentation for java.policy files

and

http://java.sun.com/developer/onlineTraining/Programming/JDCBook/appA.html

Jay Taylor
  • 13,185
  • 11
  • 60
  • 85
Petey B
  • 11,439
  • 25
  • 81
  • 101
8

Although it is not recommended, but if you really want to let your web application access a folder outside its deployment directory. You need to add following permission in java.policy file (path is as in the reply of Petey B)

permission java.io.FilePermission "your folder path", "write"

In your case it would be

permission java.io.FilePermission "S:/PDSPopulatingProgram/-", "write"

Here /- means any files or sub-folders inside this folder.

Warning: But by doing this, you are inviting some security risk.

Naved
  • 4,020
  • 4
  • 31
  • 45
  • 2
    Special thanks for mentioning "/-". On windows, it will not work with backslashes in paths (like "\-"), and I assumed the wildcard operator would be "*", which led me straight into configuration hell... – RobertG Sep 05 '14 at 09:56
1

Just document it here on Windows you need to escape the \ character:

"e:\\directory\\-"
Moshe L
  • 1,797
  • 14
  • 19
  • From the [Oracle docs on policy files](https://docs.oracle.com/javase/7/docs/technotes/guides/security/PolicyFiles.html): In order to assist in platform-independent policy files, you can also use the special notation of "${/}", which is a shortcut for "${file.separator}". This allows things like `permission java.io.FilePermission "${user.home}${/}*", "read";` – Peter Wippermann Nov 22 '21 at 10:54