Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.

Similar presentations


Presentation on theme: "Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O."— Presentation transcript:

1 Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O

2 Chapter 9 2 I/O Overview l I/O = Input/Output l the input to and output from programs l input comes from: keyboard or file l output sent to: display (screen) or file –I/O is also exchanged via network communication l Advantages of using files »permanent copy (program independent) »exchange data between programs »I/O can be automated (rather than manual) Note: Since topics on text file I/O and binary file I/O have many similarities, some duplicate (or nearly duplicate) discussions are presented.

3 Chapter 9 3 Streams l Stream: an object that either, »sends data to its destination (screen, file, etc.) or »accepts data from a source (keyboard, file, etc.) »acts as a transmission/exchange buffer between source and destination l Input stream: a stream providing input to a program l Output stream: a stream accepting output from a program »System.out is an output stream object »System.in and SavitchIn are input streams objects

4 Chapter 9 4 Binary vs. Text Files l All data and programs are stored as 0's & 1's: binary »bit is one binary digit (a 0 or 1) »byte is a group of eight (8) bits l Text files: stored bits represent characters codes »1 byte per char. for ASCII, 1 bytes for Unicode »ex: Java source code files are text files »ex: "text editor" files, rather than wordprocessor files l Binary files: stored bits represent encoded data, such as executable instructions, numeric, or images »files can only be read by the computer, not humans »they are not "printable" files, meaning the content isn't simple ASCII (or Unicode)

5 Chapter 9 5 Java: Text Versus Binary Files l Text files are more readable by humans l Binary files are more efficient »reading & writing binary files is easier than than text l Java binary files are portable »can be used by Java progs. on different machines »text files used only to communicate with humans**** Text Files l Java source code l program and system independent Binary Files l type and program specific files l are created and read by programs

6 Chapter 9 6 Text File I/O l Important classes for text file output (to a file) »PrintWriter and FileOutputStream l Important classes for text file input (from a file) »BufferedReader and FileReader Note: FileOutputStream and FileReader are used only for their constructors, to take a filename and return a file stream object »PrintWriter and BufferedReader can not use file names as arguments l Add the following to program that use files: import java.io.*;

7 Chapter 9 7 Every File Has Two Names l a file is related through two names, »the name of the file (operating system) –ex: out.txt »the identifier of the stream object (program) –ex: outputStream l a good way to think of the relation of the two names is that the, "in opening a file, the stream object is attached to the filename."

8 Chapter 9 8 Text File Output l open a text file for output: connect a text file to a stream for writing, »create a stream object of the class PrintWriter and connect it to a text file (this creates/overwrites the file) example: PrintWriter outputStream = new PrintWriter(newFileOutputStream("out.txt"); use. print() and. println() to write to the file outputStream.println(count + " " + line); (textbook lists other useful PrintWriter methods)

9 Chapter 9 9 TextFileOutputDemo Part 1 public static void main(String[] args) { PrintWriter outputStream = null; try { outputStream = new PrintWriter ( new FileOutputStream("out.txt") ); } catch(FileNotFoundException e) { // display "file opening error" and exit System.out.println(e.message()); System.exit(0); } continued...

10 Chapter 9 10 TextFileOutputDemo Part 2 String line = null; // store input int count; // loop counter System.out.println("Enter 3 lines of text:"); for (count = 1; count <= 3; count++) { line = SavitchIn.readLine(); outputStream.println (count+" "+line); } outputStream.close(); // close file System.out.println("Written to out.txt."); }// end of main()

11 Chapter 9 11 Gotcha: Overwriting a File l by default, opening a file for output, »if the file does not exist, creates an empty file »if the file exists, it is overwritten with an empty file and the original data is lost l to prevent unintentional overwrite, »check for existence of a file, using the File class (page 570); or »append data to the original file (page 551)

12 Chapter 9 12 System.out.print ("A for append, or N for new file:"); char ans = SavitchIn.readLineNonWhiteChar(); boolean append = (ans == 'A' || ans = 'a'); outputStream = new PrintWriter( new FileOutputStream("out.txt", append)); To add to a file instead of replacing it, use a different constructor for FileOutputStream : outputStream = new PrintWriter( new FileOutputStream("out.txt", true); l Second argument, true, indicates »if file exists, append output to the end, do not replace »if file does not exist, a new file is created, as expected Java Tip: Appending to a Text File

13 Chapter 9 13 Closing a File Any opened must be closed!! l this is very important for files opened for output use the close() method of the file stream »outputStream.close(); l why? »if a program crashes, there is no expectation that the OS will close open files correctly »data is stored to a memory buffer before being sent to a program (input) or a file (output); if not closed properly, this buffer may not be emptied (very bad for output)

14 Chapter 9 14 Text File Input l open a text file for input: connect a text file to a input stream for reading, »stream is of class BufferedReader »use FileReader class with BufferedReader object BufferedReader inputStream = new BufferedReader( new FileReader("datain.txt") ); »read a character ( char ) with. read() »read lines ( Strings ) with. readLine() »BufferedReader has no methods to read numerics, so "parse" strings as before (i.e., Integer.parseInt() )

15 Chapter 9 15 Exception Handling with File I/O IOException is a predefined class file I/O done as described here might throw an IOException l catch the exception in a catch-block that prints an error message and [maybe] ends the program FileNotFoundException is derived from IOException »any catch block that catches IOException s also catches FileNotFoundException s »use different catch blocks for each exception type, with more specific ones first

16 Example: Reading a File Name from the Keyboard 16 reading a file name from the keyboard using the file name read from the keyboard reading data from the file multiple catches


Download ppt "Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O."

Similar presentations


Ads by Google