One of the original fears about downloading executable content like applets from the Internet was that a hostile applet could erase your hard disk or read your Quicken files. Nothing’s happened to change that since Java was introduced. This is why Java applets run under the control of a security manager that checks each operation an applet performs to prevent potentially hostile acts.
Can an applet read a file?
Can an applet write a file?
Can an applet delete a file?
Can an applet determine whether a file exists?
Can an applet make a network connection to a particular host?
Can applet accept an incoming connection from a particular host?
The short answer to all these questions is “No, it cannot.” A slightly more elaborate answer would specify a few exceptions. Applets can make network connections to the host they came from; applets can read a few very specific files that contain information about the Java environment; and trusted applets may sometimes run without these restrictions. But for almost all practical purposes, the answer is almost always no.
For more exotic situations, such as trusted applets, see Java Security by Scott Oaks, (O’Reilly & Associates, 1998). Trusted applets are useful on corporate networks, but you shouldn’t waste a lot of time laboring under the illusion that anyone on the Internet at large will trust your applets.
Because of these security issues, you need to be careful when using
code fragments and examples from this book in an applet. Everything
shown here works when run in an application, but when run in an
applet, it may fail with a
It’s not always obvious whether a particular method or class
will cause problems. The
write() method of
BufferedOutputStream, for instance, is completely
safe when the ultimate destination is a
array. However, that same
write() method will
throw an exception when the destination is a file. An attempt to open
a connection to a web server may succeed or fail depending on whether
or not the web server you’re connecting to is the same one the
applet came from.
Consequently, this book focuses very much on applications. There is very little I/O that can be done from an applet without running afoul of the security manager. The problem may not always be obvious—not all web browsers properly report security exceptions—but it is there. If you can make an applet work when it’s run as a standalone application and you cannot get it to work inside a web browser, the problem is almost certainly a conflict with the browser’s security manager.