Chapter 19 - Files
IntroductionBy now you should all know what a file is. It can be defined loosely as a collection of data that can be referenced by a single name (the name of the file). Files can contain a lot of different things: a letter to your friend, a picture, a spreadsheet, a musical composition, code for an Applet, an actual applet, etc. Files also come in two basic types: sequential access or random access. Sequential access files may be a list of numbers that you must add up, or they could be a list of program statements like you create when you write a program. Random access files allow the user to access the data in the file at any position. In other words, you do not have to start at the beginning of the file and work your way through; you could access the 13th item, then the 2nd item, etc. A good example of a random access file would be a database. Although random access files are nice and very important, we will not discuss them in this course. We will stick to sequential access files which, in Java, are accessed via a stream.SecurityFiles are so important that they are one of the main reasons your computer has to have security built into it. In particular, let's consider a Java Applet that you download when you open up a website. You certainly do not want the creator of the website to go mucking about in the files on your computer, possibly corrupting the data in them or even deleting them from your system. Because of this, most browsers have built in a security feature that prevents all Applets from referencing files on your system. This is a good thing, but it means that if we want to write Java programs that play with files on our own computer, then we cannot write an Applet to do it. Fortunately Java allows users to write two kinds of program, Applets and Applications. An application is almost like the Applets you have written. It's just a little different in how it starts. Instead of having a class which extends an Applet, you have a class which extends a Frame, and instead of an init method, you have a main method. We'll see how this works in a minute.StreamsTo read or write to a file, you must use what's called a Java stream. Basically you do the following things:Or
- Open the file
- Read the input item by item and process it
- Close the file
To accomplish these tasks Java has a number of classes to help you. Some of them are Reader, BufferedReader, InputStreamReader, FileReader, Writer, PrintWriter, FileWriter. And each of these classes has methods for you to use.Open the file Output (write) the items you want Close the file
An Example - Writing Text Out to a FileLet's look at the textbook's example of making a program that will write some words that you type to a file:
import java.io.*;
import java.awt.*;
import java.awt.event.*;// Create the class (Note this is not an Applet)
// Also note that you are using a plain window system now,
// not a web browser
class FileDemo1 extends Frame
implements WindowListener, ActionListener {// Declare an area in the window where you can type
private TextArea inputTextArea;// Declare a button to save the data to a file
private Button saveButton;// Declare a place to hold the file name and be able
// to write to it
private PrintWriter outFile;// This is the way you create an Application instead
// of an Applet
public static void main(String [] args) {// Give this window class a name (demo)
FileDemo1 demo = new FileDemo1();// Set the window size
demo.setSize(300,400);// Allow this window to have a Graphical User
//Interface
demo.makeGui();// Put this Window on the computer screen
demo.setVisible(true);}
//Tell the system what your GUI will look like
public void makeGUI() {//Create the save button
saveButton = new Button("Save");// Place this button at the top of the window
add("North", saveButton);// add the action listener
saveButton.addActionListener(this);// Define the area where you can type stuff
inputTextArea = new TextArea(10,50);//Place this text area in the center of the window
add("Center", inputTextArea);// Add the ability to close the window
addWindowListener(this);
}// Set up for when the save button is clicked
public void actionPerformed(Actionevent evt) {if( evt.getSource() == saveButton) {
// Attempt to save the file
try {// Establish file name and the fact that you
//want to write to it
outFile = new PrintWriter (
new FileWriter("testout.txt", true);// Actually write the data to the file
outFile.print(inputTextArea.getText());// Close the file
outFile.close();}
// Go here if you cannot write to the file
catch (IOException e) {// Print an error message
System.err.println("File Error: "
+ e.toString() );// Quit
System.exit(1);}
}
}
// This will be executed if we exit cleanly by
// closing the window
public void windowClosing(WindowEvent e) {
System.exit(0)l;
}// Define the other methods to complete the
// implementation of the WindowListener
public void windowIconified(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
public void windowClosed(WindowEvent e ) {}
public void windowDeiconified(WindowEvent e ) {}
public void windowActivated(WindowEvent e ) {}
public void windowDeactiveated(WindowEvent e ) {}}
I know this program has several things that are new to you. For example we did not cover the chapters involved in setting up a graphical user interface and we did not go over how to handle error conditions with the try-catch code. If you would like to know more about these things, read chapters 16, 17, an 18 over the summer J
An Example - Reading Text in from a File
Again let's consider the example in your textbook. When you look at this example you will see a lot of parallels between it and the previous example. In fact, they are so similar that I will not include any comments in this one. You're one your own:
import java.io.*;
import java.awt.*;
import java.awt.event.*;class FileDemo2 extends Frame
implements WindowListener, ActionListener {private TextArea inputTextArea;
private Button loadButton;
private BufferedReader inFile;
private TextField nameField;public static void main(String [] args) {
FileDemo2 demo = new FileDemo2();
demo.setSize(300,400);
demo.makeGui();
demo.setVisible(true);
}public void makeGUI() {
Panel top = new Pane();
loadButton = new Button("Load");
top.add(loadButton);
loadButton.addActionListener(this);
nameField = new TextField(20);
top.add(nameField);
nameField.addActionListener(this);
add("North",top);
inputTextArea = new TextArea("",10,50);
add("Center", inputTextArea);
addWindowListener(this);}
public void actionPerformed(Actionevent evt) {
if( evt.getSource() == loadButton) {
String fileName;
fileName = nameField.getText();try {
inFile = new BufferedReader (
new FileReader(fileName);
inputTextArea.setText(" ");
String line;
while((line=inFile.readLine())!=null) {
InputTextArea.append(line+"\n");
}
inFile.close();
}
catch (IOException e) {
System.err.println("File Error: "
+ e.toString() );
System.exit(1);
}
}
}public void windowClosing(WindowEvent e) {
System.exit(0)l;
}public void windowIconified(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
public void windowClosed(WindowEvent e ) {}
public void windowDeiconified(WindowEvent e ) {}
public void windowActivated(WindowEvent e ) {}
public void windowDeactiveated(WindowEvent e ) {}
}Perhaps the only thing that needs some explanation here is the actual part that reads the file.
inFile = new BufferedReader (new FileReader( fileName));
inputTextArea.setText(" ");this line of code tells Java that you want to read something from the file while ( ( line = inFile.readLine() ) != null )this makes the text area on the screen all blank so you have a clean start InputTextArea.append( line + "\n");this reads one line from the file and places the text in the String called line and it will do this as long as it can read data (sequentially). When it reaches the end of the file and can read no more, the line string will have a null character in it and the loop will stop. this takes the line of text that was just read from the file and places a 'return' character on the end of it and then places that in the text area on the screen.
-from Java for Students, by Bell and Parr