Unformatted text preview:

Math 121: Introduction to Computing Handout #18Simple FilesThis handout contains the information about files needed to complete Assignment #4.The concept of a fileIn a certain sense, you have been working with text files all quarter. The programs thatyou have written have been stored in .java files that contain the text of your Java code.Those files, however, have been part of the program structure and not part of the data. Indeveloping practical computer-based applications, it is often important to store datapermanently in a file. Files come in many different types, but the only one that you needto be concerned with in this class is the text file, containing ASCII characters.In many ways, a text file is similar to a string. Both are ordered sequences of characters. The two critical differences are:• The information stored in a file is permanent. Data in a string variable persists only aslong as the variable does. Local variables disappear when the method returns, andinstance variables disappear when the object goes away, which typically does not occuruntil the program exits. File data exists until the file is deleted.• Files are usually read sequentially. When you read data from a file, you usually startat the beginning and read the characters in order. Once a character has been read, yougo on to the next character until you reach the end of the file.Key steps in working with files1. Declare a variable of the appropriate subclass of Reader or Writer. In Math 121, theappropriate subclass will almost always be BufferedReader for input files andPrintWriter for output files.2. Initialize that variable by calling the appropriate set of constructors, which are almostalways nested. The typical calls areBufferedReader rd = new BufferedReader(new FileReader(filename));PrintWriter wr = new PrintWriter(new FileWriter(filename));You will need to check for errors in each of these declarations as described later inthis handout.– 2 –3. Call the appropriate methods to perform the I/O operations you need. For an inputfile, these methods read data from the file into your program; for an output file, themethods transfer data from the program to the file. For now, the only operations youneed to know are readLine, which reads a single line of text from a file just as it doesfrom the console, and println, which acts just like the standard version except that itwrites its output to a file.4. Indicate that the file operations are complete by calling close. This operation iscalled closing the file and lets the operating system know that the input/outputoperations are finished.Reading lines from a fileFor the time being, the only operation you need to use to read text data from a file is thereadLine method. To understand its use, imagine for a moment that you are trying toread the file antony.txt, which has the following contents taken from Marc Antony’sfuneral oration from Julius Caesar:Friends, Romans, countrymen,Lend me your ears;I come to bury Caesar,Not to praise him.You can the open the file by callingrd = new BufferedReader(new FileReader("antony.txt"));which has the effect of establishing a link between the data file and the value of thevariable rd. The reader maintains an internal file pointer that begins before the firstcharacter of the file; I’ve indicated it here using the vertical bar in the following diagram,even though there is nothing in the actual file to mark it:|Friends, Romans, countrymen,Lend me your ears;I come to bury Caesar,Not to praise him.If you then read a line by callingline = rd.readLine();the string variable line will be set to the string– 3 –"Friends, Romans, countrymen,"and the file pointer will advance past the entire first line to the beginning of the second:Friends, Romans, countrymen,|Lend me your ears;I come to bury Caesar,Not to praise him.Eventually, after you have read all four lines of the file, the call to readLine will returnthe constant null to indicate that there is no more data in the file.Checking for errorsOpening a file is an example of an operation that can sometimes fail. For example, if yourequest the name of input file from the user, and the user types the name incorrectly, theFileReader constructor will be unable to find the file you requested. To signal failure ofthis sort, the methods in the java.io package respond by throwing an exception, whichis the name used in Java for signalling an exceptional condition outside the normal codeflow. When an exception is thrown, the program stops running the code it was executingand proceeds upward through the various stack frames until it finds a point at which thatexception is “caught.” If the exception is never caught, the program simply stops runningand the exception is reported in the Eclipse debugging window.Many of the exceptions that occur in Java, such as dividing by 0 and the like, are calledruntime exceptions and can occur at any point in the code. To make sure that clientscheck for situations like nonexistent input files, Java requires you to catch exceptions thatoccur in the java.io package using code that looks like this:BufferedReader rd = null;try { rd = new BufferedReader(new FileReader("antony.txt"));} catch (IOException ex) { Code to report or recover from the error.}In class we will discuss the example methodBufferedReader openInputFile(String prompt)– 4 –This method displays the prompt and asks the user for an input file name. If that fileexists, openInputFile returns a BufferedReader for that file. If not, openInputFileprints out a message indicating the error and gives the user another chance.Using files for outputFiles can also be used to store data written by a program. In many respects, thisoperation is easier than using files for input because you can use the println method,which works exactly like the method you’ve been using all this time. The only differenceis that you need to supply a receiver, which is a PrintWriter directed to that file. Thus,you could change the run method from HelloProgram in Chapter 2 so that the outputwould go to the file hello.txt as follows:public void run() { try { PrintWriter wr = new PrintWriter(new FileWriter("hello.txt")); wr.println("hello, world"); wr.close(); } catch (IOException ex) { println("An I/O exception has occurred");


View Full Document

REED MATH 121 - Lecture Notes

Download Lecture Notes
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Lecture Notes and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Lecture Notes 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?