1 / 14

File I/O

File I/O. Contents. Opening an input file Writing to an output file Examining the details of file I/O Using the String array parameters in function main( ) Review of input/output choices. input . txt. Executing Program. output.txt. File I/O.

catori
Download Presentation

File I/O

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. File I/O Contents • Opening an input file • Writing to an output file • Examining the details of file I/O • Using the String array parameters in function main( ) • Review of input/output choices

  2. input.txt Executing Program output.txt File I/O For many applications the input data will be stored in a file located on a disk, and the output will also be directed to a file. Must already exist when program runs Dynamically created if it doesn’t already exist

  3. Main Memory input.txt BufferedReader(fr) FileReader(“file name”) Create a BufferedReader that “wraps” around the FileReader fr A BufferedReader can read a block of text from a file, store it in a buffer in memory, and supply strings from the buffer when asked. When reading from the file has been completed, it must be closed and the connection is broken. File I/O Opening an Input File FileReader fr = new FileReader(“a:\\input.txt”); BufferedReader br = new BufferedReader(fr); String str = br.readLine( ); br.close( ); String stored here Create a FileReader with the file name and path supplied as a parameter

  4. Executing Program Main Memory output.txt FileWriter(“filename”) BufferedWriter(fw) PrintWriter(bw) buffer When finished writing to a file, you MUST close the output file to flush the remaining text out of the buffer and break the connection. Use print( ) and println( ) to write text to the buffer that will be periodically (and transparently) transferred to the file. Create a PrintWriter that wraps around the BufferedWriter to provide convenient print( ) and println( ) methods for performing output. Wrap the FileWriter fw inside of a BufferedWriter to improve efficiency. File I/O Writing to an Output file FileWriter fw = new FileWriter(“a:\\output.txt”); BufferedWriter bw = new BufferedWriter(fw); PrintWriter pw = new PrintWriter(bw); pw.println(“text text text”); pw.close( ); text text text text text text Create a FileWriter to establish a connection to an output file. If the file passed as a parameter does not exist in the specified path, it is created.

  5. The file name and path is a String escape sequence begins – character is not written to the output stream, but indicates the insertion of a special character into the string. File I/O Examine the details of file I/O When opening a file you must supply the full path and file name. If the file input.txt is located in a directory datafiles on a floppy disk, then the parameter passed to a file reader would be: FileReader fr = new FileReader(“a:\\datafiles\\input.txt”); The first backslash character is an escape character. The second backslash indicates that a backslash character is actually part of the string. “a:\\datafiles\\input.txt” For example: \t tab \n newline \\ \

  6. File I/O Examining the details of file I/O The statement sequence: FileReader fr = new FileReader(“a:\\datafiles\\input.txt”); BufferedReader br = new BufferedReader(fr); Can be written as one statement: BufferedReader br = new BufferedReader(new FileReader(“a:\\datafiles\\input.txt”)); The FileReader object, fr, is wrapped inside a BufferedReader in the first sequence of statements, and is never directly used – no messages from the code written by the programmer are directed to it. In the combined statement, the FileReader object is not given its own identifier and cannot have programmer generated messages directed to it.

  7. File I/O Examining the details of file I/O Similarly the three statements for directing output to an output file can be combined into a single statement. FileWriter fw = new FileWriter(“a:\\output.txt”); BufferedWriter bw = new BufferedWriter(fw); PrintWriter pw = new PrintWriter(bw); Are written as a single statement PrintWriter pw = new PrintWriter(new BufferedWriter( new FileWriter(“a:\\output.txt”)));

  8. File I/O Examining the details of file I/O There are a number of exceptions that may occur when working with files. The input file may not exist, the output file may be unavailable, reading from or writing to a file may cause an exception. File I/O should (must) be done inside of a try block. try { BufferedReader br = new BufferedReader(new FileReader(“input.txt”)); //do this repeatedly String str = br.readLine( ); br.close( ); //process the string str PrintWriter pw = new PrintWriter(new BufferedWriter( new FileWriter(“output.txt”))); pw.println(“output text string”); //this may be done repeatedly in a loop pw.close( ); }

  9. File I/O Explaining the details of file I/O The catch block (or blocks) must directly follow a try block. One may catch a sequence of individual IOExceptions (FileNotFound, EOF, Interrupted, etc.), or one may have a single “catch-all” catch block. Unless one intends to handle each kind of exception differently, the single catch block makes the most sense. catch (Exception e) { System.out.println(e.toString( )); exit(1); }

  10. Create a BufferedReader and attach to the input file (in same directory as the program) Create a PrintWriter to write to an output file File I/O An example import java.io.*; //for File I/O import java.util.*; //for StringTokenizer class FileIOExample { publicstaticvoid main(String [ ] args) { try { BufferedReader in = new BufferedReader(new FileReader(“input.txt”)); String inStr = in.readLine( ); //assume all input data on a single line in.close( ); double sum = 0.0, term; PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(“output.txt”))); StringTokenizer st = new StringTokenizer(inStr); while (st.hasMoreTokens( )) { term= Double.parseDouble(st.nextToken( )); out.println(term); //echo each number back to the ouput file sum +=term; } out.println(“The sum is ” + sum); out.close( ); }//end of try block //finish reading data – close the input file //flush output buffer and break connection

  11. The FileReader is wrapped inside a BufferedReader. The BufferedReader reads a block of characters into a buffer to minimize the number of disk reads. BufferedReader has a method readLine( ) that organizes the characters preceding a carriage return into a string. FileReader(“input.dat”) BufferedReader data and more text is stored in the buffer during a disk read. str “data and more text is” BufferedReader br = new BufferedReader(new FileReader(“input.txt”); File I/O Explaining the details of file I/O A FileReader is used to construct a “pipe” from a file to a program. However, it can only be used to read a single character at a time. ‘d’ ‘a’ ‘t’ ‘a’ FileReader fr = new FileReader(“input.dat”); String str; char ch = (char) fr.read( ); //called 4 times str = br.readLine( );

  12. File I/O Explaining the details of file I/O An output file behaves similarly. By wrapping a PrintWriter around a BufferedWriter each print( ) and println( ) message causes text to be written to a buffer in main memory. When the close( ) message is sent to the PrintWriter object, the message is relayed (transparently) to the BufferedWriter. The BufferedWriter writes the contents of the buffer to the disk before the connection to the output file is broken.

  13. File I/O Why the parameters String [ ] args in the header for function main? Instead of “hardwiring in” the identities of the input and output files like we have done in the previous examples – writing the names of the files directly into the code – we can supply a file name and path when we run the program by using these parameters. class FileIOExample2 { publicstaticvoid main (String [ ] args) { try { BufferedReader br = new BufferedReader(new FileReader(args[0])); PrintWriter pw = new PrintWriter(new BufferedWriter( new FileWriter(args[1]))); //rest of function } //end of try block When running this program from the command line you will type: c:>java FileIOExample2 input.txt output.txt

  14. File I/O We now have three ways of performing I/O From keyboard to screen Using Dialog Boxes Using File I/O import java.io.*; import javax.swing.*; import java.io.*; input input input BufferedReader “wraps” InputStreamReader “wraps” System.in JOptionPane. showInputDialog(“mssg”) Returns a String BufferedReader “wraps” a FileReader(“fname”) output output output System.out.println( ) JOptionPane. showMessageDialog(…) PrintWriter “wraps” BufferedWriter “wraps” FileWriter(“filename”)

More Related