Chapter XIV Topics

Total Page:16

File Type:pdf, Size:1020Kb

Chapter XIV Topics

Chapter XIV

Text Files

Chapter XIV Topics

14.1 Introduction

14.2 Different Types of Files

14.3 Reading In from Text Files

14.4 Writing Out to Text Files

14.5 Reading & Writing Simultaneously

14.6 Appending to an Existing File

14.7 Using Text Files with Graphics

14.8 Summary

Chapter XIV Text Files 1 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 jGRASP.

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.

2 Exposure Java 2015, Pre-AP®CS Edition 05-22-15 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 stage.

Data Organization This is the fundamental building block of all computer bit information – a binary digit – which stores only a 1 or 0. One byte equals 8 bits. byte The ASCII format uses 1 byte to store a character. The Unicode format uses 2 bytes to store a character. A field is one specific unit of information. field Examples: name, address, gpa, salary, diagnosis

A record consists of a set of fields for a specific purpose. Examples of the fields contained by different records: record student record: name, address, gpa, classRank employee record: name, address, salary, position patient record: name, address, diagnosis, allergies

A data base file consists of a sequence of records. Examples: A school can have a file of student records. file A business can have a file of employee records. A hospital can have a file of patient records.

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 3 14.2 Different Types of Files

It is very important to understand the difference between a file and a file data structure. This difference was actually mentioned back when Data Structures were first introduced back in chapter 11:

File Data Structure Definition

A file data structure is an internal data structure - with an unspecified number of elements of the same type - assigned to an external file name. The file data structure allows transfer of data between internal and external storage.

You will see examples of “internal file data structures” once we get to the program examples; but first, we need to understand what these internal file data structures are assigned to – specifically, the “external files”.

External File Definition

An external file is a sequence of information stored as bytes on a hard drive, disk, tape, CD, DVD, jump drive, or some other external storage device.

There can be some confusion because the term file is used to describe several different things. One might even say that it is overloaded. As with overloading, you need to look at the context to understand what type of file is being discussed. If this is a file variable that is inside a program, then it is an internal file data structure. If there are documents in a folder on your hard drive or jump drive, then these are external files. They are “external” because they exist outside of your program. If this external file it organized in such a way that it contains a sequence of records and the user can make search queries like gpa > 3.5 (which would display all records where the gpa field was 3.5 or higher) then you have a data base file.

4 Exposure Java 2015, Pre-AP®CS Edition 05-22-15 Text Files vs. Binary Files

If a file contains only a sequence of characters, it is a text file. Text files are nice and simple and can be edited by any text editor, like Notepad or jGRASP. A text file is not the same thing as a word processing document which is far more complicated. Word processing documents allow different styles like bold, underline, and italics or different fonts like Arial, Courier New, and Times New Roman. They also allow tables, margins, images and many other features. This is why we use a simple text editor like jGRASP to edit our Java program.

Word processing documents, presentation files, electronic spreadsheets, data base file and many others are all binary files. Unlike text files, binary files do not simply store text. Because of this, they cannot be edited with a text editor. Binary files have a specific format which requires a specific application for editing. .docx files can be edited with Microsoft Word; .pptx files can be edited with Microsoft PowerPoint; .xlsx files can be edited with Microsoft Excel; and .accdb files be edited with Microsoft Access (a data base manager). Keep in mind that binary files are VERY specific. Just because you have a spread sheet document, that does not mean you can load it with just any Electronic Spreadsheet software. A file created with Google Sheets might not be completely compatible with Microsoft Excel. In the same way, a file created with Microsoft PowerPoint might not be completely compatible with Google Slides.

Text Files and Binary Files

Text files contain only characters and can be edited by any text editor like Notepad or jGRASP. All Java programs are text files.

Binary files have a specific format which requires a specific application for editing.

Sequential Files vs. Random Access Files

One way to classify file is by what they store. That what we looked at when we compared text files and binary files. Another way to classify files is by how the information is accessed. To properly understand this, we need a brief history of external storage.

Chapter XIV Text Files 5 Early storage devices used long tapes on large reals. 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. It is necessary to listen to the first two songs first or fast forward to your desired selection. The same is true for VCRs (yes I know they are old fashion, but you still remember them). There is no instant way to just to your favorite scene in a movie store on video tape. Because of this, early computers, with tape storage, developed programs that could only use sequential file data access.

With time, external storage switched to disks and CDs and DVDs. 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 or DVD player. It is possible to jump directly to the third song or any other desired song on the album or CD or to jump to any scene in the movie on a DVD.

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.

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.

NOTE: In this chapter, we will strictly be working work sequential text files.

6 Exposure Java 2015, Pre-AP®CS Edition 05-22-15 14.3 Reading In from 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.

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.

Chapter XIV Text Files 7 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.

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 viewed in Notepad, jGRASP, or any other text editor.

Figure 14.1

// Java1401.java // This first program example creates an object. // The 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 // #2 { System.out.println("\nJAVA1401.JAVA\n\n"); ExpoInFile f = new ExpoInFile("Data.txt"); // #3 String inString = f.readString(); // #4 System.out.println(inString); // #5 f.closeFile(); // #6 System.out.println("\n\n"); } }

JAVA1401.JAVA

DATA.TXT FILE

8 Exposure Java 2015, Pre-AP®CS Edition 05-22-15 Figure 14.2

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 the file does not exists? Java wants to know how you, the programmer, will deal with any 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.

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 the internal file object f has been has associated 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

Chapter XIV Text Files 9 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. 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"); } }

JAVA1402.JAVA

DATA.TXT FILE

10 Exposure Java 2015, Pre-AP®CS Edition 05-22-15 This file is created to test the class. A file like this can be created with any text editor

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 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 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"); } }

JAVA1403.JAVA

DATA.TXT FILE

This file is created to test the class. A file like this can be created with any text editor like Notepad or jGRASP.

A text file should not be created with a word processor since the special formatting characters will cause confusion. null null

Chapter XIV Text Files 11 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"); } }

JAVA1404.JAVA

DATA.TXT FILE

This file is created to test the class. A file like this can be created with any text editor like Notepad or jGRASP.

A text file should not be created with a word processor since the special formatting characters will cause confusion. null

12 Exposure Java 2015, Pre-AP®CS Edition 05-22-15 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 call before the while loop and the // proper placement of the 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"); } }

JAVA1405.JAVA

DATA.TXT FILE

This file is created to test the class. A file like this can be created with any text editor like Notepad or jGRASP.

A text file should not be created with a word processor since the special formatting characters will cause confusion.

Chapter XIV Text Files 13 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 jGRASP 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"); } }

JAVA1406.JAVA

// Java0913.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 jGRASP 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(); }

14 Exposure Java 2015, Pre-AP®CS Edition 05-22-15 f.closeFile(); System.out.println("\n\n"); } } 14.4 Writing Out to 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 object. // The 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");

} }

Chapter XIV Text Files 15 Java1407.java

Java1407.txt file created

There is an easy way to get confirmation about data transfer. Load the Java1407.txt file in Notepad or jGRASP 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 method. // The 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();

16 Exposure Java 2015, Pre-AP®CS Edition 05-22-15 System.out.println("Java1408.txt file created\n\n");

} } 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 method. // The 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");

} }

Chapter XIV Text Files 17 Figure 14.13

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 object is constructed for file reading transfer. // The 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);

18 Exposure Java 2015, Pre-AP®CS Edition 05-22-15 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. Figure 14.15

Figure 14.16

Chapter XIV Text Files 19 14.6 Appending to 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. 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 {

20 Exposure Java 2015, Pre-AP®CS Edition 05-22-15 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(); } }

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.

Chapter XIV Text Files 21 Figure 14.20

Figure 14.21

// Java1412.java // This program opens up one file for input and another file for output. // The intent 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. 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(); } }

22 Exposure Java 2015, Pre-AP®CS Edition 05-22-15 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.

Figure 14.23

Figure 14.24

Chapter XIV Text Files 23 // 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(); } } 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?

24 Exposure Java 2015, Pre-AP®CS Edition 05-22-15 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 25 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 cannot simply be "thrown" in an applet. 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); } }

26 Exposure Java 2015, Pre-AP®CS Edition 05-22-15 Figure 14.26 Continued

Java is unhappy. Remember that the whole reason that we use throws IOException is that we do not want to deal with the exceptions. This works in an application, but Java does not allow it in an applet. Some people then conclude that file cannot be used in an applet at all. This is not true. An applet can access a data file if proper Exception Handling is used… which goes beyond the scope of this course.

So, it that it? No files with graphics? Well, yes and no. There is no easy way to 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. 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 27 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

28 Exposure Java 2015, Pre-AP®CS Edition 05-22-15 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 values to draw 5 circles and 1 oval 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 29 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(); } }

30 Exposure Java 2015, Pre-AP®CS Edition 05-22-15 Figure 14.29 Continued

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. 5 such text files are provided and shown in Figure 14.30. The names of the 5 files are blank.dat, Expo.dat, DK1.dat, DK2.dat, and DK3.dat.

Keep in mind that this program was taken from one of the assignments in Advanced Graphics. As such there are many advanced topics demonstrated in the program. For one thing, this IS an applet that is using a data file. Applets can read from data files if done properly; however, applets are not allowed to write to data files for Internet security reasons. The purpose of this program is to demonstrate what is possible.

Figure 14.30

Chapter XIV Text Files 31

Program Java1417.java in Figure 14.31 will ask you to enter a file name and then it will read in the file as an array of strings. It then goes through every character of every string and draws a special small square image based on what the character is.

Figure 14.31

// Java1417.java // This program is taken from one of the assignments in Advanced Graphics.

// The 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.

// This program also shows that it is possible for an applet to read // (not write) information from a file. Keep in mind that this program // demonstrated features more advanced that what is covered in Pre-AP® Computer Science. // The object here is not a complete understanding of the code. // The object is simply to demonstrate what is possible.

// When you execute this program, enter one of these file names: // DK1.dat, DK2.dat, DK3.dat, Expo.dat or blank.dat import java.io.*; import java.awt.*; import java.applet.*; import javax.swing.JOptionPane; public class Java1417 extends Applet { int numRows = 35; int numCols = 50; String background[]; String fileName;

public void init() { fileName = JOptionPane.showInputDialog("Enter file name for graphics background."); background = new String[numRows];

32 Exposure Java 2015, Pre-AP®CS Edition 05-22-15 try { BufferedReader inStream = new BufferedReader(new FileReader(fileName)); String line; int row = 0;

while((line = inStream.readLine()) != null) { background[row] = line; row++; } inStream.close(); } catch (IOException e) { System.out.println("There were problems with the code as stated below\n"); System.out.println(e.getMessage()); } System.out.println(); } 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; case '*' : drawLock(g,r,c); break; case '|' : drawPole(g,r,c); break; default : drawUnknown(g,r,c); } } public int convert(int q) { return q * 20; } public void drawSpace (Graphics g, int r, int c) { int x = convert(c); int y = convert(r); g.setColor(Color.black); g.fillRect(x,y,20,20); } public void drawGirder (Graphics g, int r, int c) { int x = convert(c); int y = convert(r); g.setColor(Color.red); g.fillRect(x,y,20,20);

Chapter XIV Text Files 33 g.setColor(Color.black); g.fillOval(x+5,y+5,10,10); g.setColor(Color.white); for(int j = 0; j<=16; j+=4) { g.drawLine(x+j,y+ 2,x+j,y+ 2); g.drawLine(x+j,y+17,x+j,y+17); } }

public void drawLadder (Graphics g, int r, int c) { int x = convert(c); int y = convert(r); g.setColor(Color.black); g.fillRect(x,y,20,20); g.setColor(Color.white); g.fillRect(x,y,4,20); g.fillRect(x+16,y,4,20); g.fillRect(x,y+8,20,4); }

public void drawHammer(Graphics g, int r, int c) { int x = convert(c); int y = convert(r); g.setColor(Color.black); g.fillRect(x,y,20,20); g.setColor(new Color(150,100,15)); g.fillRect(x,y,20,10); g.setColor(Color.yellow); g.fillRect(x+8,y+10,4,10); } public void drawBarrel (Graphics g, int r, int c) { int x = convert(c); int y = convert(r); g.setColor(Color.black); g.fillRect(x,y,20,20); g.setColor(new Color(150,100,15)); g.fillRect(x+5,y,10,20); g.fillArc(x,y,10,20,90,180); g.fillArc(x+10,y,10,20,270,180); g.setColor(Color.black); g.drawLine(x+16,y+9,x+16,y+13); g.drawLine(x+15,y+6,x+15,y+16); g.setColor(Color.white); g.drawLine(x+5,y+4,x+5,y+14); g.drawLine(x+4,y+7,x+4,y+10); g.setColor(Color.lightGray); g.drawLine(x+5,y,x+15,y); } public void drawLock (Graphics g, int r, int c) { int x = convert(c); int y = convert(r); g.setColor(Color.cyan); g.fillRect(x,y,20,5); g.setColor(Color.yellow); g.fillRect(x,y+5,20,15); }

34 Exposure Java 2015, Pre-AP®CS Edition 05-22-15 public void drawPole (Graphics g, int r, int c) { int x = convert(c); int y = convert(r); g.setColor(Color.black); g.fillRect(x,y,20,20); g.setColor(Color.cyan); g.fillRect(x+7,y,6,20); } public void drawUnknown (Graphics g, int r, int c) { int x = convert(c); int y = convert(r); g.setColor(Color.pink); g.fillRect(x,y,20,20); g.setColor(Color.black); g.drawOval(x,y,19,19); g.drawString("?",x+6,y+15); } }

Chapter XIV Text Files 35 Figure 14.31 Continued, Execution #1

36 Exposure Java 2015, Pre-AP®CS Edition 05-22-15 Figure 14.31 Continued, Execution #2

Chapter XIV Text Files 37 Figure 14.31 Continued, Execution #3

38 Exposure Java 2015, Pre-AP®CS Edition 05-22-15 Figure 14.31 Continued, Execution #4

Chapter XIV Text Files 39 Figure 14.31 Continued, Execution #5

40 Exposure Java 2015, Pre-AP®CS Edition 05-22-15 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 access with applets is more complicated that with applications. If you want to have a graphics program access a data file, it may be easier to use a graphics application. It is technically possible to read a data file from an applet, but it requires some advanced code. It is not possible for an applet to write to a data file for Internet security reasons.

Chapter XIV Text Files 41 42 Exposure Java 2015, Pre-AP®CS Edition 05-22-15

Recommended publications