Chapter 09
Chapter 09
Input and Output
Chapter Overview
Chapter 09 focuses on input and output for files and the keyboard. Crucial sections to cover include 9.1 (basic file input and output), 9.2 (representing file records as objects), 9.3 (using the File class), and 9.4 (interacting with users). Section 9.8 introduces file choosers, which will be useful to students. The remaining sections can be considered advanced material for interested students, and are not covered in the provided lecture slides.
Table of Contents
Chapter Overview 1
Table of Contents 1
Chapter Objectives 2
Introduce/Review the Concepts 2
9.1 Basic File Input and Output 2
9.1.1 Reading from a File 3
9.1.2 Writing to a File 4
9.1.3 The Structure of Files 5
9.2 Representing Records as Objects 8
9.2.1 Reading Records as Objects 8
9.2.2 File Formats 9
9.3 Using the File Class 10
9.4 Interacting with Users 11
9.5 Command Interpreters 13
9.6 Constructing a Library 13
9.7 Streams (advanced) 13
9.8 GUI: Choosers and Images 13
9.8.1 Using JFileChooser 13
9.8.2 Displaying Images from a File 14
Summary 15
9.9 Patterns 15
9.10 Concept Map 17
Assignments 17
Key Terms 18
Chapter Objectives
| |[pic] |
Introduce/Review the Concepts
9.1 Basic File Input and Output
Note that this section uses a different file than the textbook. Programs are pretty much the same. This gives students another example from which to generalize.
|This shows a file in the Notepad text editor. The data is |[pic] |
|from the 2000 United States census and shows population, | |
|number of households, median household income, and median | |
|age by county. | |
|We’ll be mostly concerned with data that is structured | |
|into fields and records. In this file, each field is | |
|separated by a tab. | |
9.1.1 Reading from a File
|Here’s the simple overview of what we want to do. The |[pic] |
|hurdles to cross include: | |
|how to specify the name (we’ll see that this is | |
|error-prone and we need to catch exceptions) | |
|how to determine if more information is available | |
|how to read the information in a record in a usable format| |
|Locate the file by passing its name when constructing a |[pic] |
|File object. Use that to construct a Scanner object, the | |
|object we’ll use to actually access the file. | |
|Problems: The file may not exist at the location | |
|specified. Have to catch a FileNotFoundException to handle| |
|that. The getMessage method prints the name of the file | |
|and the explanation that it couldn’t be found. | |
|Unfortunately, this doesn’t give the full story of where | |
|the program was looking. Print the user.dir property to | |
|get more information (the working directory). | |
|in is the name of the Scanner object used to access the |[pic] |
|information. It has methods: | |
|hasNextLine returns true if the file has another line to | |
|read. In this file, each record corresponds to one line. | |
|nextLine returns the next line of the file as a String. | |
|When we’ve finished with the file, call the close method. | |
|This allows the system to release and potentially reuse | |
|the resources required to read from the file. | |
9.1.2 Writing to a File
|This is a same program, but now it writes the matching |[pic] |
|records (lines) to a file named Alaska.txt. | |
|New lines are shown in blue. | |
|The two lines in the previous program that created the | |
|File and Scanner objects have now been combined into a | |
|single statement. | |
|The rest of the program is almost identical. The two |[pic] |
|differences: | |
|Instead of using the static object System.out to print the| |
|matching records, use the PrintWriter object we created, | |
|out. | |
|Close the output file at the end of the program’s | |
|execution. (This is much more important for output files | |
|because buffered information may not get written if the | |
|file isn’t closed.) | |
9.1.3 The Structure of Files
|Review the non-printing characters in the file (spaces, |[pic] |
|tabs, newlines). The characters used for them don’t show | |
|up correctly in the thumbnail on the right, unfortunately.| |
|They are ∙, →, and (, for space, tab, and newline, | |
|respectively. | |
|These special characters are typically used as delimiters | |
|– separators. They separate the other characters into | |
|groups, called tokens. For the most part, methods in | |
|Scanner work with tokens. | |
|Notice that tokens do not always correspond to fields | |
|(e.g.: “Fairbanks North Star”). | |
Data Acquisition Methods
|This code “pulls the record apart” so the individual |[pic] |
|pieces can be used more easily. | |
|The system maintains a “cursor” (() as it reads a file. |[pic] |
|Everything to the left of the cursor has been read; | |
|everything on the right is yet to be read. | |
|Trace the code as it reads through the records. Note that | |
|some lines of code are skipped. | |
|Point out that variables don’t change when starting to | |
|read a new record; they change when the new data is | |
|actually read. | |
When next, nextInt, and nextDouble are called, they:
• Skip delimiting characters such as tabs.
• Examine the characters up to the next delimiter.
• If the examined characters can be interpreted as the specified type, move the cursor beyond them and return the token as the specified type. If the characters can’t be interpreted as the specified type, throw a InputMismatchException and leave the cursor’s position unchanged.
The exception to the above is the nextLine method. It does not skip leading delimiters and returns the rest of the line rather than just a token.
Tokens can be read in many ways. For example, 55546 can be read with next (returning a string), nextInt, and nextDouble.
Discussion Question
The previous code (show the slide with the code) will not read the entire file correctly (show the data). Where does it go wrong and why?
This code assumes the county name is always one token. Sometimes it isn’t. For example, “Bristol Bay” or “Fairbanks North Star.” When reading the record with “Bristol Bay,” it will assign “Bristol” as the county name and then try to read “Bay” as the population.
Data Availability Methods
|Check to make sure the right kind of data is ready to be |[pic] |
|read. | |
| |[pic] |
9.2 Representing Records as Objects
9.2.1 Reading Records as Objects
|For this simple program, writing a class representing a |[pic] |
|county is admittedly more work. But any real program will | |
|need a County class anyway. Then it saves work because the| |
|program is easier to understand, write, debug … | |
| | |
|First, look at how it simplifies the method reading the | |
|file. Then look at the code for the class. | |
| |[pic] |
|The code in the County constructor is almost identical to |[pic] |
|the code we used previously. The only difference is using | |
|instance variables. | |
| |[pic] |
9.2.2 File Formats
|The format of the file – the order in which fields are |[pic] |
|stored – can have a significant effect on the code. | |
|Obviously, the second format results in easier code. | |
|There is no “law” saying a record must be on a single | |
|line. | |
|Place fields with multiple tokens at the end of the line | |
|or on a line by itself. | |
|nextLine doesn’t skip white space, so we do it ourselves | |
|by calling trim. | |
9.3 Using the File Class
|The File class is useful in its own right (besides |[pic] |
|creating Scanner objects). | |
|Valid parameters to the constructor specify a valid file | |
|name (no illegal characters!) and a location in the file | |
|system (either explicitly or implicitly). | |
|The first two examples are absolute paths (for a Windows | |
|system). | |
|The remaining three are examples of relative paths that | |
|are relative to the current working directory (assumed to | |
|be A09 in the figure). | |
|Using relative paths effectively requires knowing the | |
|current working directory. The last line will print it | |
|out. | |
| |[pic] |
9.4 Interacting with Users
|The emphasis here is on “ask the user.” |[pic] |
|To interact with the user we need to: |[pic] |
|Create a Scanner object that reads from the console rather| |
|than a file. Pass System.in rather than a file name. | |
|Prompt the user with System.out.print. | |
|Read the data with the scanner object. | |
|Reading from the console is like reading from a file | |
|except: | |
|user might make mistakes; it would be nice to recover | |
|gracefully. | |
• hard to know when we’ve reached the end of the “file” (that is, when does hasNextLine return false?). Therefore, need another strategy to end loops.
|Use a data availability method to determine if reasonable |[pic] |
|data is present. | |
|Using a while-true loop is overkill for a simple case like| |
|this. It generalizes nicely, however, for adding | |
|additional checks such as bounds checking. | |
|Note that most of this is common to reading any double | |
|from the user. Why not put it in a method? In fact, there| |
|is no instance data here, so they could be static (class) | |
|methods. | |
|By putting this in a method, we can reuse it every time we|[pic] |
|need to read a double. Better yet, put it in a library | |
|(coming soon!) so it can be easily reused in all of your | |
|programs! | |
|We can add many methods to Prompt, including things like |[pic] |
|prompting for a File (shown) or prompting for a Scanner | |
|(hinted on the slide, code in the book). The one for | |
|Scanner can include all the exception code, making opening| |
|a file really easy. | |
9.5 Command Interpreters
There are no lecture notes for this section of the text.
9.6 Constructing a Library
To be of use to your students, this section should really be customized to your own environment. Steps for using a library vary by IDE.
9.7 Streams (advanced)
This is advanced material; unless you have unusual students or course requirements, there is probably better places to put class time!
9.8 GUI: Choosers and Images
9.8.1 Using JFileChooser
|A file chooser is easier for most users than remembering |[pic] |
|and typing in a complete file name. Here is a test program| |
|for using one. | |
| | |
|The call to setCurrentDirectory is not in the text. As | |
|shown, it sets the dialog to first show the program’s | |
|current working directory. | |
9.8.2 Displaying Images from a File
|Images are often stored in files. You can write a simple |[pic] |
|image viewer as shown in these two slides. The first slide| |
|is a simple adaptation of the previous slide that uses | |
|JFileChooser. | |
|An ImageIcon can read an image from a named file. It can |[pic] |
|then be drawn at a specified position by the | |
|paintComponent method. | |
|It would be possible to draw the picture as part of a | |
|larger scene, too. | |
Summary
9.9 Patterns
| |[pic] |
| |[pic] |
| |[pic] |
| |[pic] |
| |[pic] |
9.10 Concept Map
| |[pic] |
| |[pic] |
Assignments
Any or all of the written exercises are appropriate, with the possible exception of 9.3, depending on whether you covered command interpreters.
Either of the Programming Exercises is appropriate; I lean towards 9.6 because the details of file I/O are not cluttered with other details, as in 9.5.
Round out the assignment with a Programming Project. 9.8 provides code they can reuse in later work. 9.12 is a fun one that I highly recommend. Project 9.13 combines string manipulation with file I/O and user interaction.
Key Terms
Term related to command interpreters, libraries, and streams (which are not covered in the lecture notes) are underlined and may be omitted.
absolute path—A sequence of directories separated by a special character and beginning with a known location that is used to specify the location of a file. See also: relative path.
block—To wait for user input.
buffering—Collecting information until it can all be dealt with at once. Commonly used to improve performance in input and output operations.
byte stream—An input or output stream that carries information encoded in binary and is generally not human-readable. See also: character stream, stream.
character stream—An input or output stream that carries information encoded as characters and is generally human-readable. See also: byte stream, stream.
close—To indicate that a program is finished using a file so that resources can be released.
command interpreter—A program that repeatedly accepts a (usually) textual command from a user and then interprets or executes the command.
cursor—A marker that divides a program’s input into the part that has already been read and the part that has not yet been read. Sometimes also used to refer to an insertion point.
data acquisition methods—Methods used to obtain data from an input stream such as the Scanner class. See also: data availability methods.
data availability methods—Queries used to detect the kind of data available to be read from an input stream such as the Scanner class. See also: data acquisition methods.
delimiter—A value such as a space or colon that separates other values or groups of values.
extension—The part of a file’s name following the last period and used to indicate the kind of information contained in the file.
field—One item of identifiable item of information in a record. See also: record.
file format—The design for how information is organized in a particular file.
I/O—An abbreviation for input and output.
input stream—A stream that carries information from a source to a program. See also: stream, output stream, source.
input—Information that is obtained from outside the program; for example, from the person running the program.
insertion point—The point on the console or in a user interface component where the next character typed by the user will appear.
java archive (jar) file—A single file containing many compiled classes, making the classes easier to distribute.
library—A collection of resources available to be used in many different programs. See also: package.
newline character—A character that divides two lines of text. It can be represented in a string with the character sequence ‘\n’.
open—Preparing a file for input or output.
output stream—A stream that carries information from a program to a sink or destination. See also: stream, input stream, sink.
output—Information that is produced by a program and displayed on a screen or written to a file.
package—A group of classes, usually organized around a common purpose.
processing stream—A stream that processes information as it flows from a source to a sink. See also: stream, provider stream.
prompt—An indication to the user that some action is required. A prompt is usually printed on the screen just before input is required from the user.
provider stream—A stream that provides information from a source or to a sink. See also: stream, processing stream, source, sink.
read—Obtaining input from a file or other input stream.
record—A collection of information pertaining to one thing (for example, an employee) in a file that typically contains information about many of those things. See also: field.
relative path—A sequence of directories that gives a file location relative to the current working directory. See also: absolute path, working directory.
sink—The destination for information flowing in a stream. See also: stream, source.
source—The origin of information that flows in a stream. See also: stream, sink.
stream—An ordered collection of information that moves from a source to a destination or sink. See also: input stream, output stream, character stream, byte stream, provider stream, processing stream.
token—A group of characters separated by delimiters. See also: delimiter.
whitespace—Characters such as spaces and tabs that appear as white spaces when printed on paper.
working directory—An executing program’s default directory. Files are read and written in the working directory unless their name includes an absolute or relative path.
write—The process of placing information in a file. See also: read.
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related searches
- chapter by chapter bible summary
- chapter by chapter summaries
- novel outline template chapter by chapter pdf
- chapter 9 chapter review answers
- outsiders chapter summary chapter 5
- v67 09 icd 10
- genesis chapter by chapter summary
- 3 09 exponential functions practice test
- 6 09 quiz relative and adverb clauses
- 6 09 workshop relative and adverb clauses
- chapter by chapter bible study
- chapter test b chapter 6 chemistry in biology