Java Reference
In-Depth Information
try (PrintWriter writer = new
PrintWriter(filename, "UTF-8")) {
writer.println("The first line");
writer.println("The second line");
} catch (FileNotFoundException
| UnsupportedEncodingException ex) {
System.out.println(ex);
}
return null;
},
null,
new java.io.FilePermission(filename,
"write"));
}
How It Works
In Java 8, the AccessController.doPrivileged method has been revamped,
allowing you to specify a subset of privileges that can be used in a block, rather than
executing a heightened set of privileges. The API for Privileged Blocks can be used in
the Java language to specify a different set of permissions to execute a portion of code.
To specify the permissions, you must use an AccessControl-
ler.doPrivileged block, passing a PrivilegedAction that encapsulates the
actions that require the modified permission set. The following code demonstrates the
typical use:
AccessController.doPrivileged(new
PrivilegedAction<void>(){
public void run(){
// do something privileged
}
});
The new variation of this technique allows you to specify a subset of privileges,
rather than a superset. In the recipe, a subset of privileges writes a file to disk. The new
doPrivileged method accepts three arguments, as you can see in the following
pseudocode:
Search WWH ::




Custom Search