390 likes | 539 Views
An Introduction to Java Programming and Object-Oriented Application Development. Chapter 9 File Input and Output. Objectives. In this chapter you will: Learn how bits, characters, records, and files fit into a data hierarchy Explore the differences between text files and binary files
E N D
An Introduction to Java Programming and Object-Oriented Application Development Chapter 9 File Input and Output
Objectives In this chapter you will: • Learn how bits, characters, records, and files fit into a data hierarchy • Explore the differences between text files and binary files • Use the File class to identify, manage, and manipulate files • Perform data input and output with text files • Perform data input and output with binary files An Introduction to Java Programming and Object-Oriented Application Development
File Input and Output • Most real-world applications use data files • Data stored in files are called persistent data • Reading data from a file is called file input • Writing data to a file is called file output • File processing refers to file input or file output An Introduction to Java Programming and Object-Oriented Application Development
File Input and Output (continued) • Two types of files • Text files contain only human-readable characters • Binary files contain human-readable characters and other characters understood by the software or hardware • Files containing data needed by an application may be either text or binary An Introduction to Java Programming and Object-Oriented Application Development
Inputting Data from a Text File • Many programs are designed to use external data • External data can be numeric • Stock prices, GPS coordinates temperatures • External data can be string • Names, descriptions, passwords • If such data is stored permanently in a data file, and is designed to be human-readable, it is a text file An Introduction to Java Programming and Object-Oriented Application Development
Text File Organization • Recall all data ultimately is a sequence of 0s and 1s, which represent two states of electronic circuits: on and off • A localized group of 8 bits forms a byte and bytes represent characters • Example: ‘A’ is 65 in Unicode, 01000001 in binary: 0X27+ 1X26+ 0X25+ 0X24+ 0X23+ 0X22+ 0X21+ 1X20 An Introduction to Java Programming and Object-Oriented Application Development
Text File Organization (continued) • A data field is a group of characters that has a specific meaning • Example: last_name, student_ID, test_score • A data record is a group of related fields • Example: Smith 12345 95.5 • Attributes of the same individual • A data file is a group of related data records stored in a single file An Introduction to Java Programming and Object-Oriented Application Development
Text File Organization (continued) An Introduction to Java Programming and Object-Oriented Application Development
The File Class • The File class establishes the file’s name and location and opens the file for input • If the file is in a directory other than the current, its path must be specified • The relative path is the path of folders that leads to the file relative to the current file • The absolute path is the path from the drive letter to the file • The syntax for declaring a File object: File myFl = new File (“./mydata.txt”); An Introduction to Java Programming and Object-Oriented Application Development
The FileReader and BufferedReader Classes • After the data file is established using a File object, the data in the file can be read • A source file provides data to a program • Analogous to a pipeline • The pipeline has 2 ends connected to the source (the input file) and destination (the program file) • The pipeline has a valve that controls the amount of data allowed into the program An Introduction to Java Programming and Object-Oriented Application Development
The FileReader and BufferedReader Classes (continued) An Introduction to Java Programming and Object-Oriented Application Development
The FileReader and BufferedReader Classes (continued) • Establish a data source File infl = new File (“./source.txt”); • Create a pipeline from source to program FileReader frdr = new FileReader (infl); • Create a valve BufferedReader aBfrd = new BufferedReader(frdr); An Introduction to Java Programming and Object-Oriented Application Development
The FileReader and BufferedReader Classes (continued) • Read one line of data String aRcrd = aBfrd.readLine(); • Input can also be read using the Scanner class File infl = new File (./source.txt); Scanner input = new Scanner (infl); String aFld = input.next(); An Introduction to Java Programming and Object-Oriented Application Development
Apply the Concept • Develop an application to read IDs, names, and scores of students from two different files and display the average score for each student • A while loop tests whether the program is at the end of the student names file • A nested while loop tests whether the program is at the end of the student scores file • If IDs from both files match, scores are read and totalScore and scoreCount are updated An Introduction to Java Programming and Object-Oriented Application Development
Apply the Concept (continued) • One file contains student IDs and names • A second file contains student IDs and scores • The IDs in the first file match IDs in the second file An Introduction to Java Programming and Object-Oriented Application Development
Apply the Concept (continued) An Introduction to Java Programming and Object-Oriented Application Development
Apply the Concept (continued) • File and FileNotFoundException are imported from java.io • Scanner and Formatter are imported from java.util • File objects are instantiated with the names of the input files • Scanner objects are instantiated with the File objects An Introduction to Java Programming and Object-Oriented Application Development
Apply the Concept (continued) • The main program logic is enclosed in a try block • If the input files do not exist in the same directory as the program, a FileNotFoundException is thrown • After all records have been processed, the average is computed and formatted for output • A new Scanner object is created for each record in the student scores file • A finally block closes the two data files An Introduction to Java Programming and Object-Oriented Application Development
Outputting Data to a Text File • Previously we have accessed data from a source file • Next, we output data to a destination file • A destination file receives data from a program An Introduction to Java Programming and Object-Oriented Application Development
The File Class • File objects for output are created just as for input • Unlike source files, destination files do not have to exist before the program is run • If the destination file already exists, it is overwritten when the program is run • If the destination file does not exist, it is created An Introduction to Java Programming and Object-Oriented Application Development
The File Class (continued) An Introduction to Java Programming and Object-Oriented Application Development
The FileWriter and PrintWriter Classes • Instantiate a File object to create the data destination • Instantiate a FileWriter object to create a pipeline from the program to the output file • FileWriter throws an IOException if it can’t create the output file • Instantiate a PrintWriter object to enable writing to the output file • Use the println method in PrintWriter to write the output An Introduction to Java Programming and Object-Oriented Application Development
The FileWriter and PrintWriter Classes (continued) An Introduction to Java Programming and Object-Oriented Application Development
Apply the Concept • Modify StudentScores.java to print each student’s score average to file, as well as to the command window • The application uses the same input files • Import java.io.IOException, java.io.FileWriter, and java.io.PrintWriter • Instantiate a File object for writing output • PrintWriter is declared outside of the try block to be accessible in the finally block An Introduction to Java Programming and Object-Oriented Application Development
Apply the Concept (continued) • A runtime error can occur if the output file location is nonexistent An Introduction to Java Programming and Object-Oriented Application Development
Apply the Concept (continued) An Introduction to Java Programming and Object-Oriented Application Development
Performing Input and Output with Binary Files • The previous sections discussed reading from and writing to text files • Java classes Scanner, FileReader, BufferedReader, FileWriter, and PrintWriter work with pipelines or streams that carry text data • All files not classified as text files are binary files • Binary files can be compiled programs, image files, sound files, compressed files An Introduction to Java Programming and Object-Oriented Application Development
Identifying an Input/Output File • The process of using the File class is the same for text files and binary files • Create a binary file to write to in the current directory File file1 = new File ( “./myFile.dat” ); An Introduction to Java Programming and Object-Oriented Application Development
Writing to a Binary File • To write to a text file there are 5 steps: File oFl = new File ( “averages.txt”); FileWriter fwt = new FileWriter (oFl); PrintWriter pwt = new PrintWriter (fwt); pwt.println (aLineOfData); pwt.close(); • To write to a binary file, substitute: • FileOutputStream for FileWriter • DataOutputStream for PrintWriter • writeChar for println An Introduction to Java Programming and Object-Oriented Application Development
Reading from a Binary File • To read from a binary file, identify the input file using a File object • A FileInputStream object connects the input file to the program • The DataInputStream allows different types of data to be read • Methods in DataInputStream read different types of data An Introduction to Java Programming and Object-Oriented Application Development
Reading from a Binary File (continued) An Introduction to Java Programming and Object-Oriented Application Development
Case Study: MusicWorld • Recall MusicWorld allows users to enter CD titles and the program computes the total price with tax and quantity discount • The program can be simplified by storing some of the data in a file • When the transaction is complete, it can be stored for accounting purposes • Enhancements allow reading from and writing to a file An Introduction to Java Programming and Object-Oriented Application Development
Flowcharts for New Features of MusicWorldApp9.java • String variables priceData and cdIDFromFile are added • Variables for prompting the user for input are removed • A boolean variable foundID indicates whether the CD ID entered by the user is found in the file • File, Scanner, and FileWriter objects are needed to read, tokenize, and write data An Introduction to Java Programming and Object-Oriented Application Development
Flowcharts for New Features of MusicWorldApp9.java (continued) • If the program is not at the end of the file, the CD ID is extracted from a line of data • If cdID matches cdIDFromFile, the next line of data from the price list is read • A catch block handles FileNotFoundExceptions • A new portion of the flowchart illustrates writing data to file An Introduction to Java Programming and Object-Oriented Application Development
Program Code for MusicWorldApp9.java • Line 64 calls the constructor FileWriter with two arguments • transactions.txt is the output file • true indicates the data will be appended to the file, and the file will not be overwritten • In Line 120, the while loop is given a label “whileloop” to allow the break statement in Line 129 to exit this particular loop • The Scanner constructor calls the method useDelimiter because the data is comma separated An Introduction to Java Programming and Object-Oriented Application Development
Program Code for MusicWorldApp9.java (continued) An Introduction to Java Programming and Object-Oriented Application Development
Summary • Data is arranged in a hierarchy: files, records, fields, characters, bits • The File class identifies a file to the program so that it can be read from or written to • An absolute path is the path from the drive letter to the file • A relative path is the path to the file relative to the current file • The class FileReader reads a continuous stream of characters from a text file An Introduction to Java Programming and Object-Oriented Application Development
Summary (continued) • The class BufferedReader controls the flow of characters through the FileReader object • The class FileWriter establishes a data stream from the program to a text file • The class PrintWriter enables writing formatted text to a text file • The classes FileOutputStream and DataOutputStream write program data to binary files • The classes FileInputStream and DataInputStream read data from binary files An Introduction to Java Programming and Object-Oriented Application Development