简体   繁体   中英

How to write to a file in applets in java?

Since Applets run in sandbox mode in browsers, I am using AccessController.doPrivileged to write to a file. It writes to the file when I run it in Eclipse, but doesn't write when I access the applet in browser. What am I missing? Here is the code:

public class HelloWorld extends Applet {

    public void paint(Graphics g) {
        AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
            public Boolean run() {
                try {
                    System.out.println(System.getProperty("user.home"));
                    String userHome = System.getProperty("user.home");
                    FileWriter fw = new FileWriter(userHome + File.separator
                            + "test" + File.separator + "area.txt");
                    fw.write("The area is 20m");
                    fw.flush();
                    fw.close();

                } catch (IOException ioe) {
                    System.err.println(ioe);
                }
                return Boolean.TRUE;
            }
        });
    }
}

AccessController.doPrivileged does not do what you think 1 .

But first to the two (practical) ways that an applet can access the local file system.

  • Digitally sign the applet, then have the user OK that applet when prompted.
  • Embedded applets running in a 1.6.0_10+ JRE can also access the services of the JNLP API, which include the JNLP API file services. They can work in a sand-boxed app. - they simply prompt the user when the applet goes to load or save a file. Of course, a free floating applet launched using JWS could do the same since Java 1.2, but since 1.6.0_10, those same applets can remain embedded. See the demo. of the file services in a small app. that comes complete with source, or this other small animated GIF maker for it used in an embedded applet.

You might note that I did not list 'adjust policy files/settings' in the list of practical ways. That is because it is not really practical. At least not for anything beyond a closed intranet in which the person deploying them controls the target machines (& can thereby install a policy file to allow the applet trust). But then in that situation, the benefits of an applet are severely eroded in any case.

  1. What it does is allow an applet that is already trusted to be called using a non-trusted source such as JavaScript. If adding that actually did change the security environment of an applet without lots of bells and whistles warning the end user, it would be a security bug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM