1 / 4

Files & Streams

Files & Streams. Streams and Readers. java.io package InputStream and OutputStream classes for binary bytes Reader and Writer classes for characters Reading files: FileReader class FileReader reads 1 char at a time; use BufferedReader readLine () returns null at end of file

manasa
Download Presentation

Files & Streams

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. Files & Streams

  2. Streams and Readers • java.io package • InputStream and OutputStream classes for binary bytes • Reader and Writer classes for characters • Reading files: FileReader class • FileReader reads 1 char at a time; use BufferedReader • readLine() returns null at end of file Example 1 -- reads from file on disk FileReaderfrdr = new FileReader(“filename.txt”); BufferedReaderrdr = new BufferedReader( frdr ); String line = rdr.readLine(); rdr.close(); Example 2 -- reads from keyboard BufferedReaderrdr = new BufferedReader( new InputStreamReader( System.in ));

  3. Output Streams • FileWriter • Create a FileWriter, write to it and close it. • You must write line separator characters FileWriterfw = new FileWriter(“filename.txt”); fw.write(“abcdef\n”); fw.close(); • PrintWriter • print() and println() will take of line separator characters. PrintWriterpw = new PrintWriter( new FileWriter(“filename.txt”)); pw.print( “abc “); pw.println( “def”); pw.close(); • Exceptions: IOException • File methods must be in a try/catch block for IOException

  4. Extra Credit Labs • These are optional. www.mpcfaculty.net/David_Wisneski/RockProc.java.txt and RockProc.txt instructions are in the file www.mpcfaculty.net/David_Wisneski/SimpleEdit.java.txt and SimpleEditWindowCloser.java.txt implement the recover function that saves a copy of the original file into a temp file and restores the file if user pushes undo button.

More Related