<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Java(TM) Language Basics, Part 1, Lesson 6: File Access and Permissions</TITLE>
<META NAME="AUTHOR" CONTENT="Monica Pawlan">
<META NAME="KEYWORDS" CONTENT="programming, basics, Java 2">
<META NAME="OWNER" CONTENT="Editorial/JDC">
<META NAME="revision" CONTENT="@(#)data.src 1.34 03/09/00 JDC">
<STYLE TYPE="text/css">
<!--
CODE {font-family: Courier, Monospace;
font-size: 12pt}
PRE {font-family: Courier, Monospace;
font-size: 11pt}
-->
</STYLE>
</HEAD>
<!-- Start Body Insert-->
<BODY BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#0000FF" ALINK="#FF0000" VLINK="#660066">
<!-- End Body Insert-->
<!-- Start PageTop Insert -->
<TABLE BORDER="0" CELLSPACING="0" CELLPADDING="0" WIDTH="100%">
<TR ALIGN="CENTER" VALIGN="TOP">
<TD WIDTH="157" ALIGN="LEFT">
<IMG SRC="/images/pixel.gif" HEIGHT="40" WIDTH="40" ALT="">
<A HREF="
http://java.sun.com/index.html"><IMG SRC="/images/javalogo52x88.gif" WIDTH="52" HEIGHT="88" ALT="Java Technology Home Page" BORDER="0"></A>
<BR>
<IMG SRC="/images/pixel.gif" WIDTH="157" HEIGHT="1" ALT=""></TD>
<TD>
<FORM NAME="seek1" METHOD="GET" ACTION="
http://search.java.sun.com/query.html">
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="0" WIDTH="100%">
<TR>
<TD ALIGN="RIGHT">
<IMG SRC="/images/stripelt.gif" WIDTH="6" HEIGHT="14" ALT=""></TD>
<TD WIDTH="100%">
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="0" WIDTH="100%">
<TR>
<TD BGCOLOR="#CC9966" WIDTH="100%">
<IMG SRC="/images/pixel.gif" HEIGHT="2" WIDTH="1" ALT=""></TD>
</TR>
<TR>
<TD>
<IMG SRC="/images/pixel.gif" HEIGHT="2" WIDTH="1" ALT=""></TD>
</TR>
<TR>
<TD BGCOLOR="#CC9966">
<IMG SRC="/images/pixel.gif" HEIGHT="2" WIDTH="1" ALT=""></TD>
</TR>
<TR>
<TD>
<IMG SRC="/images/pixel.gif" HEIGHT="2" WIDTH="1" ALT=""></TD>
</TR>
<TR>
<TD BGCOLOR="#CC9966">
<IMG SRC="/images/pixel.gif" HEIGHT="2" WIDTH="1" ALT=""></TD>
</TR>
<TR>
<TD>
<IMG SRC="/images/pixel.gif" HEIGHT="2" WIDTH="1" ALT=""></TD>
</TR>
<TR>
<TD BGCOLOR="#CC9966">
<IMG SRC="/images/pixel.gif" HEIGHT="2" WIDTH="1" ALT=""></TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="LEFT">
<IMG SRC="/images/stripert.gif" WIDTH="6" HEIGHT="14" ALT=""></TD>
<TD>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="0">
<TR>
<TD VALIGN="CENTER">
<A HREF="
http://java.sun.com/a-z/index.html"><IMG SRC="/images/azindex.gif" BORDER="0" WIDTH="72" HEIGHT="11" ALT="A-Z Index"></A></TD>
<TD VALIGN="CENTER">
<FONT FACE="Helvetica" SIZE="1">
<INPUT TYPE="text" SIZE="15" MAXLENGTH="128" NAME=qt></FONT></TD>
<TD VALIGN="CENTER">
<INPUT TYPE="image" SRC="/images/search.button.gif" WIDTH="55" HEIGHT="14" ALT="Search" value="search" BORDER="0"></TD>
</TR>
</TABLE>
</TD>
</TR>
</TABLE>
</FORM>
<P>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="0" CELLSPACING="0">
<TR VALIGN="TOP">
<TD WIDTH="100%"><IMG SRC="/images/chiclet.row.gif" WIDTH="55"
HEIGHT="18" ALT=""></TD>
<TD ROWSPAN="4" ALIGN="RIGHT" WIDTH="152">
<A HREF="/developer/index.html"><IMG SRC="/images/developer.connection.header.gif" BORDER="0" HEIGHT="42" WIDTH="319" ALT="Java Developer Connection(SM)"></A></TD>
</TR>
<TR VALIGN="TOP">
<TD BGCOLOR="#FFFFFF" HEIGHT="1" WIDTH="100%">
<IMG SRC="/images/pixel.gif" HEIGHT="1" WIDTH="1" ALT=""></TD>
</TR>
<TR VALIGN="TOP">
<TD BGCOLOR="#CC9966" HEIGHT="1" WIDTH="100%">
<IMG SRC="/images/pixel.gif" HEIGHT="1" WIDTH="1" ALT=""></TD>
</TR>
<TR VALIGN="TOP">
<TD><A HREF="/developer/onlineTraining/"><IMG SRC="/images/online-training.gif" WIDTH="165" HEIGHT="22" ALT="Online Training" BORDER=0></A></TD>
</TR>
</TABLE>
</TD>
</TR>
</TABLE>
<!-- End PageTop Insert -->
<!-- Start NavBar Insert -->
<TABLE BORDER="0" CELLSPACING="0" CELLPADDING="3" BGCOLOR="#FFFFFF" WIDTH="157" ALIGN="LEFT">
<!-- tab categories -->
<TR>
<TD><A HREF="
http://java.sun.com/products/"><IMG SRC="/images/side.tab.products.gif" HEIGHT="15" WIDTH="130" BORDER="0" ALT="Downloads, APIs, Documentation"></A></TD>
</TR>
<TR>
<TD><A HREF="/developer/index.html"><IMG SRC="/images/side.tab.developer.gif" HEIGHT="15" WIDTH="130" BORDER="0" ALT="Java Developer Connection"></A></TD>
</TR>
<TR>
<TD><A HREF="/developer/infodocs/index.shtml"><IMG SRC="/images/side.tab.docs.gif" HEIGHT="15" WIDTH="130" BORDER="0" ALT="Tutorials, Tech Articles, Training"></A></TD>
</TR>
<TR>
<TD><A HREF="/developer/support/index.html"><IMG SRC="/images/side.tab.support.gif" HEIGHT="15" WIDTH="130" BORDER="0" ALT="Online Support"></A></TD>
</TR>
<TR>
<TD><A HREF="/developer/community/index.html"><IMG SRC="/images/side.tab.community.gif" HEIGHT="15" WIDTH="130" BORDER="0" ALT="Community Discussion"></A></TD>
</TR>
<TR>
<TD><A HREF="
http://java.sun.com/industry/"><IMG SRC="/images/side.tab.news.gif" HEIGHT="15" WIDTH="130" BORDER="0" ALT="News & Events from Everywhere"></A></TD>
</TR>
<TR>
<TD><A HREF="
http://java.sun.com/solutions"><IMG SRC="/images/side.tab.solutions.gif" HEIGHT="15" WIDTH="130" BORDER="0" ALT="Products from Everywhere"></A></TD>
</TR>
<TR>
<TD><A HREF="
http://java.sun.com/casestudies"><IMG SRC="/images/side.tab.case.gif" HEIGHT="15" WIDTH="130" BORDER="0" ALT="How Java Technology is Used Worldwide"></A></TD>
</TR>
<TR>
<TD> <DIV ALIGN="RIGHT">
<A HREF="/servlet/PrintPageServlet"><IMG SRC="/images/printbutton.gif" WIDTH="155" HEIGHT="25" ALT="Print Button" BORDER="0"></A>
</DIV>
</TD>
</TR>
<TR><TD> </TD></TR>
<!-- End NavBar Insert -->
<!-- START SUB-NAV -->
<TR>
<TD><!-- INSERT SUB-NAV INFO -->
</TD>
</TR>
<!-- END SUB-NAV -->
</TABLE>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="0">
<TR>
<TD>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<!-- Template Version 2.0 -->
<!-- ================== -->
<!-- Start Main Content -->
<!-- ================== -->
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="0">
<TR>
<TD VALIGN="TOP">
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A NAME="top"></A>
<DIV ALIGN="RIGHT">
<FONT SIZE="-1"><A HREF="/developer/onlineTraining/index.html">Training Index</A></FONT>
<H2>Java<FONT SIZE="-2"><SUP>TM</SUP></FONT> Programming Language Basics, Part 1<BR>
<FONT SIZE="3">Lesson 6: File Access and Permissions</FONT></H2>
<FONT SIZE="-1">[<A HREF="servlet.html"><<BACK</A>] [<A HREF="index.html#contents">CONTENTS</A>] [<A HREF="dba.html">NEXT>></A>]</FONT></DIV>
<P>
So far, you have learned how to retrieve and handle a short text
string entered from the keyboard into a simple graphical user interface
(GUI). But programs also retrieve, handle, and store data in files and
databases.
<P>
This lesson expands the examples from previous lessons to perform basic
file access using the application programming interfaces (APIs)
in the <CODE>java.io</CODE> package. It also shows
you how to grant applets permission to access specific files,
and how to restrict an application so it has access to specific files
only.
<UL>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A HREF="#app">File Access by Applications</A></FONT>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A HREF="#prop">System Properties</A></FONT>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A HREF="#sep">File.separatorChar</A></FONT>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A HREF="#excep">Exception Handling</A></FONT>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A HREF="#applet">File Access by Applets</A></FONT>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A HREF="#sec">Granting Applets Permission</A></FONT>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A HREF="#res">Restricting Applications</A></FONT>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A HREF="#serv">File Access by Servlets</A></FONT>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A HREF="#append">Appending</A></FONT>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A HREF="#more">More Informattion</A></FONT>
</UL>
<HR>
<A NAME="app"></A>
<H3>File Access by Applications</H3>
The Java® 2 Platform software provides a rich range of
classes for reading character
or byte data into a program, and writing character or byte data out to an
external file, storage device, or program. The source or destination
might be on the local computer system where the program is running or
anywhere on the network.
<P>
This section shows you how to read data from
and write data to a file on the local computer system. See
<A HREF="
http://java.sun.com/docs/books/tutorial">The Java<FONT SIZE="-2"><SUP>TM</SUP></FONT> Tutorial</A>
trail on
<A HREF="
http://java.sun.com/docs/books/tutorial/essential/io/index.html">Reading
and Writing</A> for information on transferring data between programs,
between a program and memory, and performing operations such as buffering
or character encoding on data as it is read or written.
<UL>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<STRONG>Reading:</STRONG> A program opens an input <EM>stream</EM> on the
file and reads the data in serially (in the
order it was written to the file). </FONT>
<P>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<STRONG>Writing:</STRONG> A
program opens an output stream on the file and writes the data out serially.</FONT>
</UL>
This first example converts the
<A HREF="./Code/SwingUI.java">SwingUI.java</A> example from Lesson 4
to accept user input through a text field. The window on the left appears
when you start the
<A HREF="./Code/FileIO.java">FileIO</A> application, and
the window on the right appears when you click the button. When
you click the button, whatever is entered into the text field is saved to a
file. After that, another file is opened and read and its text is
displayed in the window on the right. Click again and you are back to the
original window with a blank text field ready for more input.
<P>
<TABLE>
<TR><TD WIDTH=200 ALIGN=CENTER><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<IMG SRC="./Art/fileIO1.gif" WIDTH="212" HEIGHT="" ALT="100"><P>When Application Starts</FONT>
</TD><TD ALIGN=CENTER><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<IMG SRC="./Art/fileIO2.gif" WIDTH="212" HEIGHT="101" ALT=""><P>When Button Clicked</FONT>
</TD></TR>
</TABLE>
<P>
The conversion from the <A HREF="./Code/SwingUI.java">SwingUI.java</A>
program for Lesson 4 to the <A HREF="./Code/FileIO.java">FileIO.java</A>
program for this lesson primarily involves
the <CODE>constructor</CODE> and the <CODE>actionPerformed</CODE>
method as described here.
<H4>Constructor and Instance Variable Changes</H4>
A <CODE>JTextfield</CODE> instance variable is added to
the class so the <CODE>constructor</CODE> can instantiate the object
and the <CODE>actionPerformed</CODE> method can access the text
the end user types into it.
<P>
The <CODE>constructor</CODE> instantiates the <CODE>JTextField</CODE>
with a value of 20. This value tells the Java platform the number
of columns to use to calculate the preferred width of the field.
Lower values result in a narrower display, and likewise,
higher values result in a wider display.
<P>
The <CODE>text</CODE> label is added to the
<CODE>North</CODE> section of the <CODE>BorderLayout</CODE>
so the <CODE>JTextField</CODE> can be added to the
<CODE>Center</CODE> section.
<P>
<BLOCKQUOTE>
<HR>
<STRONG>Note:</STRONG>
You can learn
more about component sizing in
<A HREF="
http://java.sun.com/docs/books/tutorial">The Java Tutorial</A>
sections on
<A HREF="
http://java.sun.com/docs/books/tutorial/ui/swingLayout/problems.html">Solving
Common Layout Problems</A>
and
<A HREF="
http://java.sun.com/docs/books/tutorial/ui/swingOverview/layout.html">Layout
Management</A>.
<HR>
</BLOCKQUOTE>
</FONT>
<PRE>
//Instance variable for text field
JTextField textField;
FileIO(){
text = new JLabel("Text to save to file:");
clicked = new
JLabel("Text retrieved from file:");
button = new JButton("Click Me");
button.addActionListener(this);
clickButton = new JButton("Click Again");
clickButton.addActionListener(this);
//Text field instantiation
textField = new JTextField(20);
panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBackground(Color.white);
getContentPane().add(panel);
//Adjustments to layout to add text field
panel.add("North", text);
panel.add("Center", textField);
panel.add("South", button);
}
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<H4>Method Changes</H4>
The <CODE>actionPerformed</CODE> method uses the
<CODE>FileInputStream</CODE> and <CODE>FileOutputStream</CODE>
classes to read data from and write data to a file.
These classes handle data in byte streams, as opposed to
character streams, which are shown in the applet
example. A more detailed explanation of the changes to the
method implementation follows the code.
</FONT>
<PRE>
public void actionPerformed(
ActionEvent event){
Object source = event.getSource();
if(source == button){
//Variable to display text read from file
String s = null;
if(_clickMeMode){
try{
//Code to write to file
String text = textField.getText();
byte b[] = text.getBytes();
String outputFileName =
System.getProperty("user.home",
File.separatorChar + "home" +
File.separatorChar + "monicap") +
File.separatorChar + "text.txt";
File outputFile = new File(outputFileName);
FileOutputStream out = new
FileOutputStream(outputFile);
out.write(b);
out.close();
//Code to read from file
String inputFileName =
System.getProperty("user.home",
File.separatorChar + "home" +
File.separatorChar + "monicap") +
File.separatorChar + "text.txt";
File inputFile = new File(inputFileName);
FileInputStream in = new
FileInputStream(inputFile);
byte bt[] = new
byte[(int)inputFile.length()];
in.read(bt);
s = new String(bt);
in.close();
}catch(java.io.IOException e){
System.out.println("Cannot access text.txt");
}
//Clear text field
textField.setText("");
//Display text read from file
text.setText("Text retrieved from file:");
textField.setText(s);
button.setText("Click Again");
_clickMeMode = false;
} else {
//Save text to file
text.setText("Text to save to file:");
textField.setText("");
button.setText("Click Me");
_clickMeMode = true;
}
}
}
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<P>
To write the end user text to a file, the text is retrieved from the
<CODE>textField</CODE> and converted to a byte array.
</FONT>
<PRE>
String text = textField.getText();
byte b[] = text.getBytes();
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<P>
Next, a <CODE>File</CODE> object is created for the file to be
written to and used to create a <CODE>FileOutputStream</CODE>
object.
</FONT>
<PRE>
String outputFileName =
System.getProperty("user.home",
File.separatorChar + "home" +
File.separatorChar + "monicap") +
File.separatorChar + "text.txt";
File outputFile = new File(outputFileName);
FileOutputStream out = new
FileOutputStream(outputFile);
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
Finally, the <CODE>FileOutputStream</CODE> object writes the byte
array to the <CODE>File</CODE> object and closes the output stream
when the operation completes.
</FONT>
<PRE>
out.write(b);
out.close();
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
The code to open a file for reading is similar.
To read text from a file, a <CODE>File</CODE> object is created
and used to create a <CODE>FileInputStream</CODE> object.
</FONT>
<PRE>
String inputFileName =
System.getProperty("user.home",
File.separatorChar + "home" +
File.separatorChar + "monicap") +
File.separatorChar + "text.txt";
File inputFile = new File(inputFileName);
FileInputStream out = new
FileInputStream(inputFile);
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
Next, a <CODE>byte</CODE> array is created the same size as
the file into which the file contents are read.
</FONT>
<PRE>
byte bt[] = new byte[(int)inputFile.length()];
in.read(bt);
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
Finally, the byte array is used to construct a <CODE>String</CODE>
object, which is used to create the text for the <CODE>label</CODE>
component. The <CODE>FileInputStream</CODE> is closed when the
operation completes.
</FONT>
<PRE>
String s = new String(bt);
label.setText(s);
in.close();
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A NAME="prop"></A>
<H4>System Properties</H4>
The above code used a call to <CODE>System.getProperty</CODE>
to create the pathname to the file in the user's home
directory. The <CODE>System</CODE> class maintains a set of
properties that define attributes of the current working
environment. When the Java platform starts, system properties
are initialized with information about the runtime
environment including the current user, Java platform
version, and the character used to separate components of a
file name (<CODE>File.separatorChar</CODE>).
<P>
The call to <CODE>System.getProperty</CODE> uses the
keyword <CODE>user.home</CODE> to get the user's home
directory and supplies the default value
<CODE>File.separatorChar + "home" + File.separatorChar + "monicap")</CODE>
in case no value is found for this key.
<A NAME="sep"></A>
<H4>File.separatorChar</H4>
The above code used the <CODE>java.io.File.separatorChar</CODE>
variable to construct the directory pathname. This variable
is initialized to contain the file separator value stored
in the <CODE>file.separator</CODE> system property and gives
you a way to construct platform-independent pathnames.
<P>
For example, the pathname <CODE>/home/monicap/text.txt</CODE>
for Unix and <CODE>\home\monicap\text.txt</CODE> for Windows
are both represented as <CODE>File.separatorChar + "home"
+ File.separatorChar + "monicap" + File.separatorChar + "text.txt"
</CODE> in a platform-independent construction.
<A NAME="excep"></A>
<H3>Exception Handling</H3>
An exception is a class that descends from either
<CODE>java.lang.Exception</CODE> or
<CODE>java.lang.RuntimeException</CODE> that defines mild
error conditions your program might encounter. Rather
than letting the program terminate, you can write code to
handle exceptions and continue program execution.
<P>
<IMG SRC="./Art/exception.gif" WIDTH="187" HEIGHT="241" ALT="" ALIGN=LEFT>
The file input and output code in the <CODE>actionPerformed</CODE>
method is enclosed in a <CODE>try</CODE> and <CODE>catch</CODE> block
to handle the <CODE>java.lang.IOException</CODE> that might be
thrown by code within the block.
<P>
<CODE>java.lang.IOException</CODE> is what is called
a checked exception. The Java platform requires that a method
catch or specify all checked exceptions that can be thrown within
the scope of a method.
<P>
Checked exceptions descend from <CODE>java.lang.Throwable</CODE>.
If a checked exception is not either caught or specified, the
compiler throws an error.
<P>
In the example, the <CODE>try</CODE> and <CODE>catch</CODE> block
catches and handles the <CODE>java.io.IOException</CODE> checked
exception. If a method does not catch a checked exception, the method
must specify that it can throw the exception because an exception that
can be thrown by a method is really part of the method's public interface.
Callers of the method must know about the exceptions that a method can
throw so they can take appropriate actions.
<P>
However, the <CODE>actionPerformed</CODE> method already has
a public interface definition that cannot be changed to specify the
<CODE>java.io.IOException</CODE>, so in this case, the only
thing to do is catch and handle the checked exception. Methods you
define yourself can either specify exceptions or catch and handle
them, while methods you override must catch and handle checked
exceptions. Here is an example of a user-defined method that
specifies an exception so callers of this method can catch
and handle it:
</FONT>
<PRE>
public int aComputationMethod(int number1,
int number2)
throws IllegalValueException{
//Body of method
}
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<BLOCKQUOTE>
<HR>
<STRONG>Note:</STRONG>
You can find more information on this topic in
<A HREF="
http://java.sun.com/docs/books/tutorial/">The
Java Tutorial</A> trail on
<A HREF="
http://java.sun.com/docs/books/tutorial/essential/exceptions">Handling
Errors with Exceptions</A>.
<HR>
</BLOCKQUOTE>
<P>
When you catch exceptions in your code, you should handle them
in a way that is friendly to your end users. The exception
and error classes have a <CODE>toString</CODE> method to print system
error text and a <CODE>printStackTrace</CODE> method to print
a stack trace, which can be very useful for debugging your application
during development. But, it is probably better
to deploy the program with a more user-friendly approach to handling
errors.
<P>
You can provide your own application-specific error text
to print to the command line, or display a dialog box with
application-specific error text. Using application-specific
error text that you provide will also make it much easier to
internationalize the application later on because you will
have access to the text.
<P>
For the example programs in this lesson, the error message
for the file input and output is handled with application-specific
error text that prints at the command line as follows:
<PRE>
//Do this during development
}catch(java.io.IOException e){
System.out.println(e.toString());
System.out.println(e.printStackTrace());
}
//But deploy it like this
}catch(java.io.IOException e){
System.out.println("Cannot access text.txt");
}
</PRE>
If you want to make your code even more user friendly, you
could separate the write and read operations and
provide two <CODE>try</CODE> and <CODE>catch</CODE>
blocks. The error text for the read operation could
be <EM>Cannot read text.txt</EM>, and the error text for
the write operation could be <EM>Cannot write text.txt</EM>.
<P>
As an exercise, change the code to handle the read
and write operations separately. Give it a try before
peeking at the <A HREF="./Code/FileIOError.java">solution</A>.
<A NAME="applet"></A>
<H3>File Access by Applets</H3>
The file access code for the
<A HREF="./Code/FileIOAppl.java">FileIOAppl.java</A>
code is equivalent to the FileIO.java application, but shows
how to use the APIs for handling data in character streams instead
of byte streams. You can use either approach in applets or applications.
In this lesson, the choice to handle data in bytes streams in the application
and in character streams in the applet is purely random. In real-life
programs, you would base the decision on your specific application
requirements.
<P>
The changes to instance variables and the <CODE>constructor</CODE> are
identical to the application code, and the changes to the
<CODE>actionPerformed</CODE> method are nearly identical with
these two exceptions:
<UL>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<STRONG>Writing:</STRONG> When the <CODE>textField</CODE> text is
retrieved, it is passed directly to the <CODE>out.write</CODE> call.</FONT>
<P>
<LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<STRONG>Reading:</STRONG> A character array is created
to store the data read in from the input stream. </FONT>
</UL>
</FONT>
<PRE>
public void actionPerformed(ActionEvent event){
Object source = event.getSource();
if(source == button){
//Variable to display text read from file
String s = null;
if(_clickMeMode){
try{
//Code to write to file
String text = textField.getText();
String outputFileName =
System.getProperty("user.home",
File.separatorChar + "home" +
File.separatorChar + "monicap") +
File.separatorChar + "text.txt";
File outputFile = new File(outputFileName);
FileWriter out = new
FileWriter(outputFile);
out.write(text);
out.close();
//Code to read from file
String inputFileName =
System.getProperty("user.home",
File.separatorChar + "home" +
File.separatorChar + "monicap") +
File.separatorChar + "text.txt";
File inputFile = new File(inputFileName);
FileReader in = new FileReader(inputFile);
char c[] = new
char[(char)inputFile.length()];
in.read(c);
s = new String(c);
in.close();
}catch(java.io.IOException e){
System.out.println("Cannot access text.txt");
}
//Clear text field
textField.setText("");
//Display text read from file
text.setText("Text retrieved from file:");
textField.setText(s);
button.setText("Click Again");
_clickMeMode = false;
} else {
//Save text to file
text.setText("Text to save to file:");
textField.setText("");
button.setText("Click Me");
_clickMeMode = true;
}
}
}
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A NAME="sec"></A>
<H3>Granting Applets Permission</H3>
If you tried to run the applet example, you undoubtedly
saw errors when you clicked the <CODE>Click Me</CODE> button. This is
because the Java 2 Platform security does not permit an applet
to write to and read from files without explicit permission.
<P>
An applet has no access to local system resources unless it
is specifically granted the access. So for the <CODE>FileUIAppl</CODE>
program to read from <CODE>text.txt</CODE> and write to
<CODE>text.txt</CODE>, the applet has to be given the appropriate read
or write access permission for each file.
<P>
Access permission is granted with a policy file, and appletviewer
is launched with the policy file to be used for the applet
being viewed.
<H4>Creating a Policy File</H4>
Policy tool is a Java 2 Platform security tool for creating policy files.
<A HREF="
http://java.sun.com/docs/books/tutorial/">The Java Tutorial</A>
trail on
<A HREF="
http://java.sun.com/docs/books/tutorial/security1.2/tour1/step2.html">Controlling Applets</A> explains how to use Policy Tool in good detail.
Here is the policy file you need to run the applet. You can use
Policy tool to create it or copy the text below into an ASCII file.
</FONT>
<PRE>
grant {
permission java.util.PropertyPermission
"user.home", "read";
permission java.io.FilePermission
"${user.home}/text.txt", "read,write";
};
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<H4>Running an Applet with a Policy File</H4>
Assuming the policy file is named <CODE>polfile</CODE> and
is in the same directory with an HTML file named
<CODE>fileIO.html</CODE> that contains the HTML
to run the <CODE>FileIOAppl</CODE> applet, you would run the
application in appletviewer like this:
</FONT>
<PRE>
appletviewer -J-Djava.security.policy=polfile fileIO.html
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<BLOCKQUOTE>
<HR>
<STRONG>Note:</STRONG>
If your browser is enabled for the Java 2 Platform or if you
have <A HREF="
http://java.sun.com/products/plugin/index.html">Java
Plug-in</A> installed, you
can run the applet from the browser if you put the policy file
in your local home directory.
<HR>
</BLOCKQUOTE>
Here is the <CODE>fileIO.html</CODE> file for running the <CODE>FileIOAppl</CODE>
applet:
</FONT>
<PRE>
<HTML>
<BODY>
<APPLET CODE=FileIOAppl.class WIDTH=200 HEIGHT=100>
</APPLET>
</BODY>
</HTML>
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A NAME="res"></A>
<H3>Restricting Applications</H3>
You can use the default security manager and a policy file
to restrict the application's access as follows.
</FONT>
<PRE>
java -Djava.security.manager
-Djava.security.policy=apppolfile FileIO
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
Because the application runs within the security manager, which disallows
all access, the policy file needs two additional permissions. One so
the security manager can access the event queue and load the user interface
components, and another so the application does not display
the banner warning that its window was created by another
program (the security manager).
</FONT>
<PRE>
grant {
permission java.awt.AWTPermission
"accessEventQueue";
permission java.awt.AWTPermission
"showWindowWithoutWarningBanner";
permission java.util.PropertyPermission
"user.home", "read";
permission java.io.FilePermission
"${user.home}/text.txt", "read,write";
};
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A NAME="serv"></A>
<H3>File Access by Servlets</H3>
Although servlets are invoked from a browser, they are under the
security policy in force for the web server under which they run. When
file input and output code is added to <CODE>ExampServlet.java</CODE>
from Lesson 5, <A HREF="./Code/FileIOServlet.java">FileIOServlet</A>
for this lesson executes without restriction under Java WebServer<FONT SIZE="-2"><SUP>TM</SUP></FONT> 1.1.1.
<P>
<IMG SRC="./Art/servIO1.gif" WIDTH="297" HEIGHT="205" ALT="">
<TABLE BORDER="2" CELLSPACING="2" CELLPADDING="2">
<TR><TD>
<IMG SRC="./Art/servIO2.gif" WIDTH="313" HEIGHT="115" ALT="">
</TD></TR>
</TABLE>
</FONT>
<PRE>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FileIOServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<title>Example<title>" +
"<body bgcolor=FFFFFF>");
out.println("<h2>Button Clicked</h2>");
String DATA = request.getParameter("DATA");
if(DATA != null){
out.println("<STRONG>Text from
form:</STRONG>");
out.println(DATA);
} else {
out.println("No text entered.");
}
try{
//Code to write to file
String outputFileName=
System.getProperty("user.home",
File.separatorChar + "home" +
File.separatorChar + "monicap") +
File.separatorChar + "text.txt";
File outputFile = new File(outputFileName);
FileWriter fout = new FileWriter(outputFile);
fout.write(DATA);
fout.close();
//Code to read from file
String inputFileName =
System.getProperty("user.home",
File.separatorChar + "home" +
File.separatorChar + "monicap") +
File.separatorChar + "text.txt";
File inputFile = new File(inputFileName);
FileReader fin = new
FileReader(inputFile);
char c[] = new
char[(char)inputFile.length()];
int i;
i = fin.read(c);
String s = new String(c);
out.println("<P>
<STRONG>Text from file:</STRONG>");
out.println(s);
fin.close();
}catch(java.io.IOException e){
System.out.println("Cannot access text.txt");
}
out.println("<P>Return to
<A HREF="../simpleHTML.html">Form</A>");
out.close();
}
}
</PRE>
<FONT FACE="Verdana, Arial, Helvetica, sans-serif">
<A NAME="append"></A>
<H3>Appending</H3>
So far the examples have shown you how to read in and
write out streams of data in their entirety. But often,
you want to append data to an existing file or read in
only certain amounts. Using the
<A HREF="
http://java.sun.com/products/jdk/1.2/docs/api/java/io/RandomAccessFile.html">RandomAccessFile</A>
class, alter the <A HREF="./Code/FileIO.java">FileIO.java</A>
class to append to the file.
<P>
Give it a try before taking a peek at the
<A HREF="./Code/AppendIO.java">Solution</A>.
<A NAME="more"></A>
<H3>More Information</H3>
For more infomation on file input and output, see the
<A HREF="
http://java.sun.com/docs/books/tutorial/essential/io/index.html">Reading
and Writing</A> trail in
<A HREF="
http://java.sun.com/docs/books/tutorial">The Java Tutorial</A>.
<P>
You can learn more about component sizing in
<A HREF="
http://java.sun.com/docs/books/tutorial">The Java Tutorial</A>
sections on
<A HREF="
http://java.sun.com/docs/books/tutorial/ui/swingLayout/problems.html">Solving
Common Layout Problems</A>
and
<A HREF="
http://java.sun.com/docs/books/tutorial/ui/swingOverview/layout.html">Layout
Management</A>.
<P ALIGN="RIGHT">
<FONT SIZE="-1">[<A HREF="#top">TOP</A>]</FONT>
</FONT>
</TD>
</TR>
</TABLE>
<!-- ================ -->
<!-- End Main Content -->
<!-- ================ -->
</FONT>
</TD>
</TR>
</TABLE>
<!-- Copyright Insert -->
<BR CLEAR="ALL">
<FORM ACTION="/cgi-bin/search.cgi" METHOD="POST">
<TABLE WIDTH="100%" CELLPADDING="0" BORDER="0" CELLSPACING="5">
<TR>
<TD VALIGN="BOTTOM">
</TD>
</TR>
<A HREF="/servlet/PrintPageServlet"><IMG SRC="/images/printbutton.gif" WIDTH="155" HEIGHT="25" ALT="Print Button" BORDER="0"></A>
<CENTER>
<FONT SIZE="-1" COLOR="#999999" FACE="Verdana, Arial, Helvetica, sans-serif">
[ This page was updated: <!-- new date --> 31-Mar-2000 ]
</font></CENTER>
</TD>
</TR>
<TR>
<TD BGCOLOR="#CCCCCC">
<IMG SRC="/images/pixel.gif" HEIGHT="1" WIDTH="1" ALT=""></TD>
</TR>
<TR>
<TD>
<CENTER>
<FONT SIZE="-2" FACE="Verdana, Arial, Helvetica, sans-serif">
<A HREF="
http://java.sun.com/products/">Products & APIs</A> |
<A HREF="/developer/index.html">Developer Connection</A> |
<A HREF="/developer/infodocs/index.shtml">Docs & Training</A> |
<A HREF="/developer/support/index.html">Online Support</A><BR>
<A HREF="/developer/community/index.html">Community Discussion</A> |
<A HREF="
http://java.sun.com/industry/">Industry News</A> |
<A HREF="
http://java.sun.com/solutions">Solutions Marketplace</A> |
<A HREF="
http://java.sun.com/casestudies">Case Studies</A>
</FONT>
</CENTER>
</TD>
</TR>
<TR>
<TD BGCOLOR="#CCCCCC">
<IMG SRC="/images/pixel.gif" HEIGHT="1" WIDTH="1" ALT=""></TD>
</TR>
<TR>
<TD ALIGN="CENTER">
<FONT SIZE="-2" FACE="Verdana, Arial, Helvetica, sans-serif">
<A HREF="
http://java.sun.com/docs/glossary.html">Glossary</A> -
<A HREF="
http://java.sun.com/applets/">Applets</A> -
<A HREF="
http://java.sun.com/docs/books/tutorial/">Tutorial</A> -
<A HREF="
http://java.sun.com/jobs/">Employment</A> -
<A HREF="
http://java.sun.com/nav/business/">Business & Licensing</A> -
<A HREF="
http://java.sun.com/javastore/">Java Store</A> -
<A HREF="
http://java.sun.com/casestudies/">Java in the Real World</A>
</FONT>
</TD>
</TR>
<TR>
<TD>
<CENTER>
<FONT SIZE="-2" FACE="Verdana, Arial, Helvetica, sans-serif">
<a href="/siteinfo/faq.html">FAQ</a> |
<a href="/feedback/index.html">Feedback</a> |
<a href="
http://www.dynamicdiagrams.net/mapa/cgi-bin/help.tcl?db=javasoft&dest=
http://java.sun.com/">Map</a> |
<A HREF="
http://java.sun.com/a-z/index.html">A-Z Index</A>
</FONT>
</CENTER>
</TD>
</TR>
<TR>
<TD>
<TABLE WIDTH="100%" CELLPADDING="0" BORDER="0" CELLSPACING="0">
<TR>
<TD WIDTH="50%">
<FONT SIZE="-2" FACE="Verdana, Arial, Helvetica, sans-serif">
For more information on Java technology<BR>
and other software from Sun Microsystems, call:<BR>
</FONT>
<FONT SIZE="-1" FACE="Verdana, Arial, Helvetica, sans-serif">
(800) 786-7638<BR></FONT>
<FONT SIZE="-2" FACE="Verdana, Arial, Helvetica, sans-serif">
Outside the U.S. and Canada, dial your country's
<A HREF="
http://www.att.com/business_traveler/attdirecttollfree/">AT&T Direct Access Number</A> first.<BR>
</FONT>
</TD>
<TD ALIGN="RIGHT" WIDTH="50%">
<A HREF="
http://www.sun.com"><IMG SRC="/images/lgsun.gif" width="64" height="30" border="0" ALT="Sun Microsystems, Inc."></A><BR>
<FONT SIZE="-2" FACE="Verdana, Arial, Helvetica, sans-serif">
Copyright © 1995-2000
<A HREF="
http://www.sun.com">Sun Microsystems, Inc.</A><BR>
All Rights Reserved.
<A HREF="
http://www.sun.com/share/text/termsofuse.html">Terms of Use</A>.
<A HREF="
http://www.sun.com/privacy/">Privacy Policy</A>.
</FONT>
</TD>
</TR>
</TABLE>
</TD>
</TR>
</TABLE>
</FORM>
<!-- End Copyright Insert -->
</BODY>
</HTML>