1 / 38

An Introduction to Java Programming and Object-Oriented Application Development

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

hashim
Download Presentation

An Introduction to Java Programming and Object-Oriented Application Development

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. An Introduction to Java Programming and Object-Oriented Application Development Chapter 9 File Input and Output

  2. 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

  3. 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

  4. 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

  5. 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

  6. 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

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

  8. Text File Organization (continued) An Introduction to Java Programming and Object-Oriented Application Development

  9. 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

  10. 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

  11. The FileReader and BufferedReader Classes (continued) An Introduction to Java Programming and Object-Oriented Application Development

  12. 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

  13. 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

  14. 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

  15. 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

  16. Apply the Concept (continued) An Introduction to Java Programming and Object-Oriented Application Development

  17. 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

  18. 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

  19. 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

  20. 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

  21. The File Class (continued) An Introduction to Java Programming and Object-Oriented Application Development

  22. 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

  23. The FileWriter and PrintWriter Classes (continued) An Introduction to Java Programming and Object-Oriented Application Development

  24. 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

  25. 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

  26. Apply the Concept (continued) An Introduction to Java Programming and Object-Oriented Application Development

  27. 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

  28. 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

  29. 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

  30. 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

  31. Reading from a Binary File (continued) An Introduction to Java Programming and Object-Oriented Application Development

  32. 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

  33. 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

  34. 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

  35. 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

  36. Program Code for MusicWorldApp9.java (continued) An Introduction to Java Programming and Object-Oriented Application Development

  37. 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

  38. 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

More Related