Download Text14-TextFiles

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Chapter XIV
Text Files
Chapter XVI Topics
14.1
Introduction
14.2
Different Types of Files
14.3
Reading In Text Files
14.4
Writing Out Text Files
14.5
Reading & Writing Simultaneously
14.6
Appending an Existing File
14.7
Using Text Files with Graphics
14.8
Summary
Chapter XIV Text Files
501
14.1 Introduction
Random Access Memory (RAM) is great while it lasts, but it is only temporary.
Rebooting the computer, flipping the power switch, tripping over the power cord
and enjoying a friendly electrical storm can quickly delete or corrupt the
information stored in your computer’s dynamic memory.
Long ago, you became familiar with the solution to this problem. Use external
storage to permanently store any important information. Most students learn
several lessons about the virtue of saving their work on a regular basis. Common
software programs like word processors, spreadsheets, and program languages,
like Java, create user data files that are stored externally.
This means that the program you write is in fact a data file of another program.
This may seem odd. You probably are comfortable thinking that a word
processing document is stored as a data file. However, the programs you have
written seem like programs, not data files. Both are true simultaneously. You
have written fully functional Java programs. At the same time, the programs you
have written were data files of some text editor program, like Notepad or a special
Integrated Development Environment (IDE) program, like JCreator.
Program languages in general - and Java specifically - have the ability to create
their own data files. This means that data entered by a program user can be stored
for future processing. It also means that data only needs to be entered once. In
some cases, data never needs to be entered. It is quite possible that your teacher,
or somebody else, has created a data file of information. It becomes your job to
retrieve that information in your program and process the data. This approach is
very convenient and used quite extensively in college computer science classes.
Programs and Data Files Notes
Data information processed by word processing, spreadsheet
and similar application programs are stored as data files.
Java programs, written with a text editor or some Integrated
Development Environment (IDE), are also data files.
Programs have the capability to create and retrieve their own
data files. This means that data entered in any one of your
programs can be saved for later use.
502
Exposure Java 2012, PreAPCS Edition
05-16-12
The most fundamental justification for using a computer is to process information
or data. Frequently, data need to be transferred from some external storage to
internal memory or newly processed internal data need to be stored externally for
future processing needs. The word data is tossed around in computer science in
general and it certainly is mentioned every other sentence already in this chapter.
What exactly is data, and how does it fit in with this file business? Computer data
forms an organized hierarchy of information. Data starts at the very humble bit
and works up the ranks to byte, field, record and file. Let's look at each one of
these stages.
Data Organization
bit
This is the fundamental building block of all computer
information, a binary digit, which stores only 1 or 0.
byte
One byte equals 8 bits.
One character can be stored in one byte, using ASCII code.
One character is stored in two bytes using Unicode.
field
A field is one specific unit of information of one data type,
such as size, age, name, date, etc.
record
A record consists of a set of fields for some specific purpose,
such as a student record, a medical record, an employee
record, an airline passenger record, etc.
file
A file is a sequence of records of the same type.
The transfer of data between internal memory and external storage is quite a
complicated process. Modern languages like C++ and Java use streams to handle
data transfer. A stream is a set of bytes or characters. In the old days there was
no distinction between bytes and characters. Now that Unicode, with its two-byte
characters is in use, there is a distinction. Think of a stream as a pipeline that
contains a neatly ordered set of data. Streams can go in two directions; for input
and for output. Input streams can come from the keyboard, from an external
storage source, or mouse-click. Output streams can go to the monitor, an external
storage location or the printer. Streams allow consistent input/output processing
for many different types of sources and destinations.
Chapter XIV Text Files
503
14.2 Different Types of Files
It is very important to understand the difference between a file and a file data
structure. It is easier to explain what a file is. Working on a computer means
working with files. Files contain information used by some application program.
So what is a file? You just saw this data hierarchy, and it appears that a file is a
sequence of related records. From the computer's point of view a file only holds
information. The programmer organizes the information in files, in records of
fields and so on. A file really is nothing more than a sequence of information
stored on a disk. The manner in which the data is accessed varies but the file
itself is a bunch of information coded on a disk or other storage device.
File Definition
A file is a sequence of information stored as bytes on a
disk, tape, jump drive, CD or other external storage device.
Understanding files is assisted by a brief history lesson of external storage. Early
storage devices used long tapes on large disks. Accessing information on such
tapes was only possible in sequence. Reading or writing information with tape
storage required sequential access. Most students are familiar with this process.
Pop an audiotape in a player and try to play the third song. It is necessary to
listen to the first two songs first or fast forward to your desired selection. Either
way, it is not possible to access the requested song directly. Access on a tape is
sequential. Early computers with tape storage developed programs that could
only use sequential file data access.
With time, external storage switched to disks and CDs. Such devices allow direct
access of certain files. This type of access is called random access. You can
randomly access file information. This type of access is similar to an old record
album player or CD player. It is possible to jump directly to the third song or any
other desired song on the album or CD.
Random access of files may be handled in a future computer science course. In
this first file introduction we will only concentrate on sequential files. After you
have worked with sequential files, it will be a comfortable transition to add the
additional processing required to manage random access files.
504
Exposure Java 2012, PreAPCS Edition
05-16-12
Sequential Access and Random Access
Files can have sequential access or random access.
Sequential access files allow data access only in the
sequence that the data is stored in the file.
Random access files allow data access in any random
pattern, regardless of how the data is stored.
14.3 Reading In Text Files
Data information cannot casually transfer from an external hard drive to internal
memory. Data stored in electronic memory locations requires some special
process to communicate with a keyboard, a monitor, a printer or a hard drive. In
each case a buffer is needed for data transfer.
A buffer is a temporary memory location, but it is more than a location where data
can sit and wait for transfer. The data is handled differently in various situations.
Consider the following analogy. A person walks at roughly 3 mph. A jet flies at
an average speed of 550 mph. How is it possible for a very slow person to switch
travel speed from very slow to very fast? The answer is a buffer. In the case of
transfer from walking to flying, the buffer is an airport. The airport does have a
waiting lounge at the gate and that resembles temporary memory. Something else
is going on, because the plane is no longer traveling at 550 mph, but rather lands
at the airport and comes to a complete stop outside your gate. It is now possible
for the data (people and luggage in this case) to transfer to the plane. Without the
airport transfer of people from walking to flying is impossible. The same is true
with a computer. Data switches between internal storage and external storage in a
file buffer.
Chapter XIV Text Files
505
The Java language has a very rich assortment of classes to handle file processes.
There are more than sixty classes and it is necessary to use multiple classes to
transfer data, first from memory to file buffer, and then continue from file buffer
to external storage. At a first introduction this type of file processing is quite
complicated and this chapter will handle files with the aid of the ExpoInFile and
ExpoOutFile classes. These two classes are cousins of the Expo class, which
you have used throughout this course to learn programming logic. You will
transfer data between internal electronic memory and external file locations, but
for now some training wheels will make matters simpler. A future course will
provide more detail.
Buffers
A buffer is a temporary memory location.
Additionally, a buffer manages the transfer of data between
different computer segments, such as keyboard, printer,
monitor and external storage devices.
File Buffer
A file buffer is a buffer that transfers data between internal
electronic memory, RAM, and external data storage on a hard
drive, CD drive or jump drive.
Data files can stores different information in different modes. The most common
type of data is a text file. A text file stores characters and can be viewed with any
text file editor, like NotePad or JCreator. Data files can also store binary
information and other types of formats. In this chapter we shall only be
concerned with files of characters, called text files.
506
Exposure Java 2012, PreAPCS Edition
05-16-12
Program Java1401.java, in figure 14.1, opens a file object for input and reads in
one string of text file data from an external file, called Data.txt. Six program
lines are identified with numerical comments. Each one of these lines will be
revisited and discussed in detail. Look at the program execution first and then
analyze the line-by-line sequence of the program execution. The output shows a
single line of text from the external DATA.TXT text file. Figure 14.2 shows the
actual contents of the text file. This can be views in Notepad, JCreator, or any
other text editor.
Figure 14.1
// Java1401.java
// This first program example creates an <ExpoInfile> object.
// The <readString> method transfers an individual string from an external
// hard drive file to internal file object.
import java.io.*;
// #1
public class Java1401
{
public static void main (String args[]) throws IOException
{
System.out.println("\nJAVA1401.JAVA\n\n");
ExpoInFile f = new ExpoInFile("Data.txt");
String inString = f.readString();
System.out.println(inString);
f.closeFile();
System.out.println("\n\n");
}
}
// #2
// #3
// #4
// #5
// #6
Figure 14.2
Chapter XIV Text Files
507
We will now examine each one of the significant program lines to understand the
file handling sequence. You may be surprised why the methods shown here were
not added to the Expo class. The Expo class is convenient and allows many
different type of program features. On the other hand, good program design is
based on creating classes for a specific purpose.
import java.io.*;
// #1
Line #1 uses a Java standard input/output library, which provides access to
classes for file handling.
public static void main (String args[ ]) throws IOException
// #2
Line #2 adds the keywords throws IOException. This is required by the Java
language. File handling, also known as input/output or IO, can have a variety of
problems. For instance, what happens if you try to transfer data from a file that
does not exists? Java wants to know how you, the programmer, will deal with
potential IO problems. We will choose to tell Java not to get excited. We literally
tell Java to throw away or ignore any input/output errors that may occur. In other
words we are taking responsibility for any program execution problems.
ExpoInFile f = new ExpoInFile("Data.txt");
// #3
Line #3 creates an f object of the ExpoInFile class. The f file structure is
constructed with Data.txt. This means that f has associated the internal file
object f with the external text file Data.txt. The ExpoInFile class contains
methods for the transfer of data from external storage to internal memory. This is
known as opening a file for input.
String inString = f.readString();
// #4
Line #4 gets down to the business of actually transferring one string of data from
the Data.txt file to internal memory with the readString method. The single line
of characters is stored in the memory location of the inString variable.
508
Exposure Java 2012, PreAPCS Edition
05-16-12
System.out.println(inString);
// #5
Line #5 displays the value of the inString variable. This lets you see the first line
of the Data.txt file.
f.closeFile();
// #6
Line#6 concludes the file handling by closing the file object. Failure to close a
file object can result in data loss. Think of it as closing the chicken coop after you
pick up the eggs.
Program Java1402.java, in figure 14.3, presents no new methods. This time the
readString method is called four times and displays the first four lines of the
Data.txt file.
Figure 14.3
// Java1402.java
// This program demonstrates how to read in four lines from
// the external "Data.txt" file.
import java.io.*;
public class Java1402
{
public static void main (String args[]) throws IOException
{
System.out.println("\nJAVA1402.JAVA\n\n");
ExpoInFile f = new ExpoInFile("Data.txt");
System.out.println(f.readString());
System.out.println(f.readString());
System.out.println(f.readString());
System.out.println(f.readString());
f.closeFile();
System.out.println("\n\n");
}
}
Chapter XIV Text Files
509
Reading in one line of a text file with one program statement is not very efficient.
This is precisely why there are control structures like repetition loops. Program
Java1403.java, in figure 14.4, uses a for loop to read in ten lines of the data.txt
file. This may work correctly if you know that there are ten lines in the text file.
In this case there are only eight lines. The program attempts to read in two strings
that do not exist. The output provides two nulls. Keyword null indicates an
object with no value.
Figure 14.4
// Java1403.java
// This program uses a <for> loop to read in file data.
// A fixed loop structure can cause problems, because the
// precise file size might not be known.
// The last couple of <null> outputs indicate that there was no
// more string data in the external text file.
import java.io.*;
public class Java1403
{
public static void main (String args[]) throws IOException
{
System.out.println("\nJAVA1403.JAVA\n\n");
ExpoInFile f = new ExpoInFile("Data.txt");
for (int k = 1; k <= 10; k++)
System.out.println(f.readString());
f.closeFile();
System.out.println("\n\n");
}
}
510
Exposure Java 2012, PreAPCS Edition
05-16-12
Program Java1404.java, in figure 14.5, attempts to be clever. This time we use a
conditional while loop. The condition checks to see if the String object has a
null value. It may seem like a good approach, but the program still executes one
line beyond the last string in the data file.
Figure 14.5
// Java1404.java
// This program attempts to read in a text file using a conditional
// loop. It seems to work, but it still reads in one line past the
// end of the file.
import java.io.*;
public class Java1404
{
public static void main (String args[]) throws IOException
{
System.out.println("\nJAVA1404.JAVA\n\n");
ExpoInFile f = new ExpoInFile("Data.txt");
String inString = " ";
while(inString != null)
{
inString = f.readString();
System.out.println(inString);
}
f.closeFile();
System.out.println("\n\n");
}
}
Chapter XIV Text Files
511
Program Java1405.java, in figure 14.6, works correctly. The secret is that the
statement String inString = f.readString(); is first placed before the while
conditional statement. It is now possible to check if the file is possibly empty. At
the same time inside the while loop the same input statement is repeated at the
end of the loop body. This eliminates the extra null statement from reading past
the last line of characters.
Figure 14.6
// Java1405.java
// This program reads in the text file correctly.
// The <readString> call before the while loop and the
// proper placement of the <readString> call inside the
// loop body cures the problem.
import java.io.*;
public class Java1405
{
public static void main (String args[]) throws IOException
{
System.out.println("\nJAVA1405.JAVA\n\n");
ExpoInFile f = new ExpoInFile("Data.txt");
String inString = f.readString();
while(inString != null)
{
System.out.println(inString);
inString = f.readString();
}
f.closeFile();
System.out.println("\n\n");
}
}
512
Exposure Java 2012, PreAPCS Edition
05-16-12
The next program will prove that a Java program is indeed a text file. The
program is the same as the previous program, but now it is not Data.txt that is
used as the text file, but the program itself. Figure 14.7 shows that the output of
the program execution of Java1406.java is the program itself.
Figure 14.7
// Java1406.java
// This program demonstrates that it is possible for a program
// to read in itself, since a java program is a text file.
// Some of the tabs used in JCreator may look a little strange.
import java.io.*;
public class Java1406
{
public static void main (String args[]) throws IOException
{
System.out.println("\nJAVA1406.JAVA\n\n");
ExpoInFile f = new ExpoInFile("Java1406.java");
String inString = f.readString();
while(inString != null)
{
System.out.println(inString);
inString = f.readString();
}
f.closeFile();
System.out.println("\n\n");
}
}
Chapter XIV Text Files
513
14.4 Writing Out Text Files
When you are working with sequential text files a decision must be made to open
a file object for input or for output. The previous section used the ExpoInfile
class to construct file objects for input. This section will use the ExpoOutFile
class to construct objects for output. Constructing an object for input or output is
identical. The internal file object, called f again, must be associated with an
external file, which is Java1407.txt. Program Java1407.java, in figure 14.8,
intentionally uses the same file object identifier, f that was used previously. The
name of the file object is inconsequential. The difference is in the class. You will
note in figure 14.8 that the import statement is used the same, as is the throws
IOException statement. Also the construction of the file object is identical
(except for using a different class) and closing the file is the same. The key
difference is the highlighted statement, which uses the writeString method to
transfer a string of internal data to the external file. The program output window
states that the Java1407.txt is created, but there is little evidence otherwise that
any data was transferred.
Figure 14.8
// Java1407.java
// This program example creates an <ExpoOutfile> object.
// The <writeString> method transfers an individual string from internal
// file object to external hard drive file.
import java.io.*;
public class Java1407
{
public static void main (String args[]) throws IOException
{
System.out.println("Java1407.java");
String inString;
ExpoOutFile f = new ExpoOutFile("Java1407.txt");
System.out.println();
f.writeString("The quick brown fox jumps over the lazy dog.");
f.closeFile();
System.out.println("Java1407.txt file created\n\n");
}
}
514
Exposure Java 2012, PreAPCS Edition
05-16-12
There is an easy way to get confirmation about data transfer. Load the
Java1407.txt file in Notepad or JCreator and you will see, in fact, that the data
was sent. Figure 14.9 shows there is one line in the file, which is the sentence you
saw in the program.
Figure 14.9
Program Java1408.java, in figure 14.10, uses five writeString method calls. This
program is designed to demonstrate that method writeString does not include a
line feed. Figure 14.11 displays the contents of the Java 1408.txt file and you
will notice that all five outputs are on the same line. The reason this happened is
we did not send a linefeed.
Figure 14.10
// Java1408.java
// This program transfers five strings from internal memory to an
// external hard drive file with the <writeString> method.
// The <writeString> method does not provide a line feed.
import java.io.*;
public class Java1408
{
public static void main (String args[]) throws IOException
{
System.out.println("Java1408.java");
String inString;
ExpoOutFile f = new ExpoOutFile("Java1408.txt");
System.out.println();
f.writeString("Line-1 ");
f.writeString("Line-2 ");
f.writeString("Line-3 ");
f.writeString("Line-4 ");
f.writeString("Line-5 ");
f.closeFile();
System.out.println("Java1408.txt file created\n\n");
}
}
Chapter XIV Text Files
515
Figure 14.11
It is possible to include a linefeed. There is another method in ExpoOutFile,
called writelnString. The same exact logic is used as with the print and println
methods. When a stream of information is sent for output the computer does not
care whether the destination is the monitor, printer or a file. Linefeeds are treated
the exact same way. Program Java1409.java, in figure 14.12, uses the
writelnString method. Figure 14.13 shows the resulting storage in the data file.
Figure 14.12
// Java1409.java
// This program transfers five strings from internal memory to an
// external hard drive file with the <writelnString> method.
// The <writelnString> method does provide a line feed.
import java.io.*;
public class Java1409
{
public static void main (String args[]) throws IOException
{
System.out.println("Java1409.java");
String inString;
ExpoOutFile f = new ExpoOutFile("Java1409.txt");
System.out.println();
f.writelnString("Line-1 ");
f.writelnString("Line-2 ");
f.writelnString("Line-3 ");
f.writelnString("Line-4 ");
f.writelnString("Line-5 ");
f.closeFile();
System.out.println("Java1409.txt file created\n\n");
}
}
Figure 14.13
516
Exposure Java 2012, PreAPCS Edition
05-16-12
14.5 Reading & Writing Simultaneously
The first nine program examples either opened a file object for input or for output.
Can a program handle input and output at the same time? The answer is yes and
no. You cannot use the same file object for input and output. However, there is
no problem with constructing two file objects in the same program. Program
Java1410.java, in figure 14.14, constructs file object input for input and file
object output for output. In this program the input object reads every string from
the Java1410a.txt file and then the output object takes each string and transfers it
out to the Java1410b.txt file.
Figure 14.14
// Java1410.java
// This program creates two file objects in the same program.
// The <input> object is constructed for file reading transfer.
// The <output> object is constructed for file writing transfer.
// The result is that the "Java1410b.txt" file becomes a copy of the
// "Java1410a.txt" text file.
import java.io.*;
public class Java1410
{
public static void main (String args[]) throws IOException
{
System.out.println("Java1410.java\n\n");
ExpoInFile input = new ExpoInFile("Java1410a.txt");
ExpoOutFile output = new ExpoOutFile("Java1410b.txt");
String inString = input.readString();
while(inString != null)
{
output.writelnString(inString);
inString = input.readString();
}
input.closeFile();
output.closeFile();
}
}
Text file Java1410a.txt stores five lines of text, as shown in figure 14.15. The
next display in figure 14.16 shows that the contents have been copied completely
in the new text file.
Chapter XIV Text Files
517
Figure 14.15
Figure 14.16
14.6 Appending an Existing File
In this section we are going to explore adding data to an existing text file.
Consider that every previous program example used to create a text file, created
its own file and stored data. Now what would happen if a file already exists and
you start to write information to that file? Look at figure 14.17; it contains the
data of the Java1411.txt file. This existing text file will be used to test our next
program example.
518
Exposure Java 2012, PreAPCS Edition
05-16-12
Figure 14.17
Now you know that a text file already exists. Program Java1411.java, in figure
14.18, opens a file object for output associated with the existing Java1411.txt
file. Two strings are transferred to the data file. What will happen to the existing
data file? Will the new data append to the end of the existing file or will the
existing data be destroyed?
Figure 14.18
// Java1411.java
// This program demonstrates the consequence of opening a file
// for output that already exist. Will the next information be added
// to the end of the file, or will the file be destroyed?
import java.io.*;
public class Java1411
{
public static void main (String args[]) throws IOException
{
System.out.println("Java1411.java\n\n");
ExpoOutFile output = new ExpoOutFile("Java1411.txt");
output.writelnString("Java 1411, line 1");
output.writelnString("Java 1411, line 2");
output.closeFile();
}
}
Chapter XIV Text Files
519
Figure 14.19
The output in figure 14.19 tells the story. The data of the existing file is totally
gone and replaced by the data transfer of the current program. This is a reality
that must be appreciated. It is quite easy to destroy the contents of a file.
So how does one add new data to an existing file? How about trying the
following approach? Open a file for input, read in the file data, and then store the
data in a String array. Now turn around and open the same file for output,
transfer the array information, followed by the new data.
Program
Java1412.java, in figure 14.21, performs the very steps just mentioned. Figure
14.20 displays the contents of the Java1412.txt file before executing the program.
Figure 14.22 display the file contents after program execution.
Figure 14.20
Figure 14.21
// Java1412.java
// This program opens up one file for input and another file for output.
// The intend is to read in the file, store the data in an array and
// then write the data back to the file, followed by new data.
520
Exposure Java 2012, PreAPCS Edition
05-16-12
import java.io.*;
public class Java1412
{
public static void main (String args[]) throws IOException
{
System.out.println("Java1412.java\n\n");
ExpoInFile input = new ExpoInFile("Java1412.txt");
ExpoOutFile output = new ExpoOutFile("Java1412.txt");
String temp[] = new String[1000];
int index = 0;
temp[index] = input.readString();
while(temp[index] != null)
{
index++;
temp[index] = input.readString();
}
input.closeFile();
for (int k = 0; k < index-1; k++)
output.writelnString(temp[k]);
output.writelnString("Java 1412, line 1");
output.writelnString("Java 1412, line 2");
output.closeFile();
}
}
Figure 14.22
We thought we were clever, but the program did not work. Somehow the original
data is lost and the text file contains only the new data. What went wrong? This
program example was intentionally used to prove a point. Constructing a new file
object for output destroys the existing file. In program Java1412.java a file is
opened for output before any data is stored in a temporary array. Our clever
scheme does not use the correct sequence.
So let us try it again with a few significant changes. Once again we show the
sequence of text file contents before execution - program source code - text file
contents after execution. Figure 14.23 shows the Java1413.txt file, which is the
same old file. Figure 14.24 shows program Java1413.java and figure 14.25
displays the contents after the program execution.
Chapter XIV Text Files
521
Figure 14.23
Figure 14.24
// Java1413.java
// This program updates an existing file correctly.
// The secret is that the data information is stored before the file object for output is constructed.
import java.io.*;
public class Java1413
{
public static void main (String args[]) throws IOException
{
System.out.println("Java1413.java\n\n");
ExpoInFile input = new ExpoInFile("Java1413.txt");
String temp[] = new String[1000];
int index = 0;
String inString = input.readString();
while(inString != null)
{
temp[index] = inString;
index++;
inString = input.readString();
}
input.closeFile();
ExpoOutFile output = new ExpoOutFile("Java1413.txt");
for (int k = 0; k < index; k++)
output.writelnString(temp[k]);
output.writelnString("Java 1413, line 1");
output.writelnString("Java 1413, line 2");
output.closeFile();
}
}
522
Exposure Java 2012, PreAPCS Edition
05-16-12
Figure 14.25
The program now works correctly. Notice what would happen if you execute the
program multiple times. Do the successive outputs make sense?
Figure 14.25 Continued
It is possible with the limited file tools of the ExpoInFile and ExpoOutFile
classes to read in data from a file, write out data to a file and update an existing
file. The process of adding data to the end of an existing file is called appending
a file. There are more efficient ways to append a file than is shown in this
chapter. Right now a few basic file handling techniques were shown to provide a
foundation for future file handling.
Chapter XIV Text Files
523
14.7 Using Text Files with Graphics
Throughout this chapter we have seen various programs that manipulate text files.
The data stored in these text files is useful for the programs that read from them or
write to them. So far, all of the file handling examples have been text programs.
Can they be used with a graphics program?
Program Java1414.java, in figure 14.26, tries to read in the text file used by the
previous program, Java1413.java, and then display its contents on a Java Applet
Window.
Figure 14.26
// Java1414.java
// This program tries to read in the first 6 lines of line from
// the file "Java1413.txt" and display them on an Applet Window.
// This will not work because files cannot be used with applets.
import java.applet.Applet;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JOptionPane;
public class Java1414 extends Applet
{
String line1, line2, line3, line4, line5, line6;
public void init() throws IOException
{
ExpoInFile file = new ExpoInFile("Java1413.txt");
line1 = file.readString();
line2 = file.readString();
line3 = file.readString();
line4 = file.readString();
line5 = file.readString();
line6 = file.readString();
file.closeFile();
}
public void paint(Graphics g)
{
Expo.setFont(g,"Algerian",Font.BOLD+Font.ITALIC,72);
Expo.drawString(g,line1,20,100);
Expo.drawString(g,line2,20,200);
Expo.drawString(g,line3,20,300);
Expo.drawString(g,line4,20,400);
Expo.drawString(g,line5,20,500);
Expo.drawString(g,line6,20,600);
}
}
524
Exposure Java 2012, PreAPCS Edition
05-16-12
Figure 14.26 Continued
Java is unhappy. Rather than try to explain the exact meaning of the error
message just accept this one fact. Files cannot be accessed from an applet… at
least, not without understanding more advanced concepts that go beyond this first
year course.
So, it that it? No files with graphics? Well, yes and no. We cannot access files
from a Java Applet, but you can access files from a Java Graphics Application. All
of the application programs that you have seen this year have been Text
Applications. Program Java1415.java, in figure 14.27, is the first Graphics
Application. You will notice that like an applet, a graphics application has a
paint method; however, like all applications, it also has a main method. The
main method in a graphics application is rather complex. The one part that is
somewhat clear is the setSize method which is setting the size of the graphics
window. You may remember that for an applet, this is done in the .html file.
Remember that an application does not use an .html file. Having graphics does
not change this. This means you will compile and execute the same file.
Figure 14.27
// Java1415.java
// This program is able to read data from a file and display it on a
// graphics screen because it is an "application" and not an "applet".
// Since this is an application you compile and execute the same file.
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JOptionPane;
public class Java1415
{
public static void main(String args[]) throws IOException
{
GfxApp gfx = new GfxApp();
gfx.setSize(1000,650);
gfx.addWindowListener(new WindowAdapter() {public void
windowClosing(WindowEvent e) {System.exit(0);}});
gfx.readFile();
gfx.show();
}
}
Chapter XIV Text Files
525
class GfxApp extends Frame
{
String line1, line2, line3, line4, line5, line6;
public void paint(Graphics g)
{
Expo.setFont(g,"Algerian",Font.BOLD+Font.ITALIC,72);
Expo.drawString(g,line1,20,100);
Expo.drawString(g,line2,20,200);
Expo.drawString(g,line3,20,300);
Expo.drawString(g,line4,20,400);
Expo.drawString(g,line5,20,500);
Expo.drawString(g,line6,20,600);
}
public void readFile() throws IOException
{
ExpoInFile file = new ExpoInFile("Java1413.txt");
line1 = file.readString();
line2 = file.readString();
line3 = file.readString();
line4 = file.readString();
line5 = file.readString();
line6 = file.readString();
file.closeFile();
}
}
Figure 14.27 Continued
526
Exposure Java 2012, PreAPCS Edition
05-16-12
The data file Java1416.txt, in figure 14.28, is used by program Java1416.java in
figure 14.29. The 19 numbers in the data file will be read and used to draw a 5
circles and 1 oval to make the face that you see in the output. To prove that the
numbers in the text file are controlling the program, alter them and rerun the
program. You will see that the output has changed.
Figure 14.28
Figure 14.29
// Java1416.java
// This program reads 19 strings from a file, converts them to integers,
// and them uses the int values to draw 4 circles on the graphics screen.
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JOptionPane;
public class Java1416
{
public static void main(String args[]) throws IOException
{
GfxApp gfx = new GfxApp();
gfx.setSize(1000,650);
gfx.addWindowListener(new WindowAdapter() {public void
windowClosing(WindowEvent e) {System.exit(0);}});
gfx.readFile();
gfx.show();
}
}
Chapter XIV Text Files
527
class GfxApp extends Frame
{
int x1, x2, x3, x4, x5, x6;
int y1, y2, y3, y4, y5, y6;
int r1, r2, r3, r4, r5, r6, r7;
public void paint(Graphics g)
{
Expo.drawCircle(g,x1,y1,r1);
Expo.drawCircle(g,x2,y2,r2);
Expo.drawCircle(g,x3,y3,r3);
Expo.fillCircle(g,x4,y4,r4);
Expo.fillCircle(g,x5,y5,r5);
Expo.drawOval(g,x6,y6,r6,r7);
}
public void readFile() throws IOException
{
ExpoInFile file = new ExpoInFile("Java1416.txt");
x1 = Integer.parseInt(file.readString());
y1 = Integer.parseInt(file.readString());
r1 = Integer.parseInt(file.readString());
x2 = Integer.parseInt(file.readString());
y2 = Integer.parseInt(file.readString());
r2 = Integer.parseInt(file.readString());
x3 = Integer.parseInt(file.readString());
y3 = Integer.parseInt(file.readString());
r3 = Integer.parseInt(file.readString());
x4 = Integer.parseInt(file.readString());
y4 = Integer.parseInt(file.readString());
r4 = Integer.parseInt(file.readString());
x5 = Integer.parseInt(file.readString());
y5 = Integer.parseInt(file.readString());
r5 = Integer.parseInt(file.readString());
x6 = Integer.parseInt(file.readString());
y6 = Integer.parseInt(file.readString());
r6 = Integer.parseInt(file.readString());
r7 = Integer.parseInt(file.readString());
file.closeFile();
}
}
Figure 14.29 Continued
528
Exposure Java 2012, PreAPCS Edition
05-16-12
Text files can be quite useful in graphics programs. Graphics backgrounds can
take up quite a bit of memory. If the graphics background is stored as text and
then converted to graphics very little memory is used. You also have an easy way
to manipulate the background.
The final program in this chapter can work with a variety of text files. 3 such text
files are provided and shown in figure 14.30. The names of the 3 files are
blank.dat, Expo.dat and DK.dat.
Figure 14.30
Program Java1417.java in figure 14.31 will ask you to enter a file name and then
read in the file as an array of strings. It then goes through every character of
every string and draw a special small square image based on what the character is.
Figure 14.31
// Java1417.java
// This program reads text from a file whose name is entered by the user.
// Each character in the file is tied to a specific graphics image.
// By manipulating the text files, you can manipulate the background.
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JOptionPane;
public class Java1417
{
public static void main(String args[]) throws IOException
{
GfxApp gfx = new GfxApp();
gfx.setSize(1024,768);
gfx.addWindowListener(new WindowAdapter() {public void
windowClosing(WindowEvent e) {System.exit(0);}});
gfx.readFile();
gfx.show();
}
}
Chapter XIV Text Files
529
class GfxApp extends Frame
{
int numRows = 36; // 35 Rows are displayed. The top row (row 0) it hidden behind the title bar.
int numCols = 50;
String background[];
String fileName;
public void paint(Graphics g)
{
for (int r = 0; r < numRows; r++)
for (int c = 0; c < numCols; c++)
switch(background[r].charAt(c))
{
case '.' : drawSpace(g,r,c); break;
case '=' : drawGirder(g,r,c); break;
case '#' : drawLadder(g,r,c); break;
case 'H' : drawHammer(g,r,c); break;
case 'B' : drawBarrel(g,r,c); break;
default : drawUnknown(g,r,c);
}
}
public void readFile() throws IOException
{
fileName = JOptionPane.showInputDialog("Enter file name for graphics background.");
background = new String[numRows];
ExpoInFile file = new ExpoInFile(fileName);
int row = 0;
String line = file.readString();
while(line != null)
{
background[row] = line;
row++;
line = file.readString();
}
file.closeFile();
}
public int convert(int q)
{
q*=20;
q+=10;
return q;
}
public void drawSpace (Graphics g, int y, int x)
{
x = convert(x);
y = convert(y);
Expo.setColor(g,Expo.black);
Expo.fillRectangle(g,x,y,x+19,y+19);
}
public void drawGirder (Graphics g, int y, int x)
{
x = convert(x);
y = convert(y);
Expo.setColor(g,Expo.red);
Expo.fillRectangle(g,x,y,x+19,y+19);
Expo.setColor(g,Expo.black);
Expo.fillCircle(g,x+10,y+10,5);
Expo.setColor(g,Expo.white);
for(int j = 0; j<=16; j+=4)
{
Expo.drawLine(g,x+j,y+2,x+j,y+2);
Expo.drawLine(g,x+j,y+17,x+j,y+17);
}
}
530
Exposure Java 2012, PreAPCS Edition
05-16-12
public void drawLadder (Graphics g, int y, int x)
{
x = convert(x);
y = convert(y);
Expo.setColor(g,Expo.black);
Expo.fillRectangle(g,x,y,x+19,y+19);
Expo.setColor(g,Expo.white);
Expo.fillRectangle(g,x,y,x+3,y+19);
Expo.fillRectangle(g,x+16,y,x+19,y+19);
Expo.fillRectangle(g,x,y+8,x+19,y+11);
}
public void drawHammer(Graphics g, int y, int x)
{
x = convert(x);
y = convert(y);
Expo.setColor(g,Expo.black);
Expo.fillRectangle(g,x,y,x+19,y+19);
Expo.setColor(g,Expo.brown);
Expo.fillRectangle(g,x,y,x+19,y+9);
Expo.setColor(g,Expo.yellow);
Expo.fillRectangle(g,x+8,y+10,x+11,x+19);
}
public void drawBarrel (Graphics g, int y, int x)
{
x = convert(x);
y = convert(y);
Expo.setColor(g,Expo.black);
Expo.fillRectangle(g,x,y,x+19,y+19);
Expo.setColor(g,Expo.brown);
Expo.fillRectangle(g,x+5,y,x+14,y+19);
Expo.fillArc(g,x+6,y+10,5,10,180,0);
Expo.fillArc(g,x+14,y+10,5,10,0,180);
Expo.setColor(g,Expo.black);
Expo.drawLine(g,x+16,y+9,x+16,y+13);
Expo.drawLine(g,x+15,y+6,x+15,y+16);
Expo.setColor(g,Expo.white);
Expo.drawLine(g,x+5,y+4,x+5,y+14);
Expo.drawLine(g,x+4,y+7,x+4,y+10);
Expo.setColor(g,Expo.lightGray);
Expo.drawLine(g,x+5,y,x+15,y);
}
public void drawUnknown (Graphics g, int y, int x)
{
x = convert(x);
y = convert(y);
Expo.setColor(g,Expo.pink);
Expo.fillRectangle(g,x,y,x+19,y+19);
Expo.setColor(g,Expo.black);
Expo.drawCircle(g,x+10,y+9,8);
Expo.drawString(g,"?",x+7,y+14);
}
}
Chapter XIV Text Files
531
Figure 14.31 Continued, Execution #1
532
Exposure Java 2012, PreAPCS Edition
05-16-12
Figure 14.31 Continued, Execution #2
Chapter XIV Text Files
533
Figure 14.31 Continued, Execution #3
534
Exposure Java 2012, PreAPCS Edition
05-16-12
14.8 Summary
Data information processed by word processing, spreadsheet, or other application
programs is stored as data files.
Java programs written with a text editor or some Integrated Development
Environment (IDE) are also data files.
Programs have the capability to create and retrieve their own data files. This
means that data entered in any one of your programs can be saved for later use.
Programs can be tested with existing data files for greater efficiency.
A file is a sequence of information stored as bytes on a disk, tape, CD or other
external storage device.
Files can have sequential access or random access. Sequential access files allow
data access only in the sequence that the data is stored in the file. Random
access files allow data access in any random pattern, regardless of how the data is
stored.
When data is transferred between internal memory and external storage a file
buffer is needed to handle the transfer. A buffer is a temporary memory location
where data is able to switch between different data management facilities, like the
fully electronic RAM and the electro-mechanical hard drive.
Java has more than sixty file classes for a large variety of file processing needs.
This chapter only uses two classes, which are not part of the Java standard library
file classes. They are the ExpoInFile class and the ExpoOutFile class. Like the
Expo class, these classes are meant to teach real computer science concepts in a
more user-friendly environment.
The ExpoInFile class uses the readString method to transfer data from external
storage to internal memory. The ExpoOutFile class uses the writeString and
writelnString methods to transfer data from internal memory to external storage.
Both file classes use the closeFile method to discontinue the use of a file object.
File handling is not permitted with Java Applets for internet security reasons. If
you want to use text files with graphics, you need to create a Java Graphics
Application. When working with Java Graphics Applications, there is no .html
file. You compile and execute the .java file just like any other Java Application.
Chapter XIV Text Files
535
536
Exposure Java 2012, PreAPCS Edition
05-16-12