50 likes | 177 Views
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
E N D
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 ));
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
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.