LECTURE 8 NOVEMBER 2004 ASSIGNMENTS Today 6:00 PM Assignment 3 Code Fri CodeLab #10 What? - reading and writing files FILE INPUT What? - using files as input - aka reading files What? - representing a file in java - store info about a file in a particular location How? - java.io.File What? - paths How? - where something is located on your computer What? - full path: from the drive (Windows), or root (unix), including all of the directories on the way down - relative path: assumes the current directory and just specifies the name What? - creating a file handle in Java - File constructor takes a string with the name of the file Example File f1 = new File("1108.txt"); File f2 = new File("~/cs302/public/html/cs302/lecture/"); What? - reading a file - a file is just a sequence of 1's and 0's stored in memory - to be able to read it, have to assume that these make sense as ASCII How? - use BufferedReader - instead of initializing with System.in, initialize with a File - like System.in, need an intermediate class: FileReader instead of InputStreamReader What? - java.io.FileStreamReader - translates file data bytes into a stream of characters How? - constructor - takes a File object or a String which is the file name - throws a FileNotFoundException if it can't find a matching file What? - reading a file How? - initialize BufferedReader with an instance of FileStreamReader initialized with a File object representing the file to be read - use the readLine method to read a line of the file Example: BufferedReader fileIn = new BufferedReader ( new FileReader ( "1108.txt" ) ); What? - file reading issues - remember that readLine can cause an IOException which must be caught or propagated - readLine will return null if there's nothing left to read - use the new BufferedReader instance method close() to close the file when you are done reading it Example: - write a class to read a file and echo this output to the console