230 likes | 390 Views
Files from Ch4. File Input and Output. Reentering data all the time could get tedious for the user. The data can be saved to a file. Files can be input files or output files . Files: Files have to be opened. Data is then written to the file.
E N D
File Input and Output • Reentering data all the time could get tedious for the user. • The data can be saved to a file. • Files can be input files or output files. • Files: • Files have to be opened. • Data is then written to the file. • The file must be closed prior to program termination. • In general, there are two types of files: • binary • text
Writing Data To a File • Objects from the following classes are used to write data to files: • FileWriter – This class allows basic file writing functionality. • PrintWriter – This class allows the programmer to write files using the same style that is used to write to the screen (i.e. print and println).
The FileWriter Class • The FileWriter clas provides other classes with the basic file writing functionality. System.out.println(“Enter the filename.”); filename = Keyboard.readString(); FileWriter fwriter = new FileWriter(filename); • This will create an object that can access the file filename. • Warning: if the file already exists, it will be erased and replaced with the new file.
The PrintWriter Class • The PrintWriter class adds to the functionality of the FileWriter class. • The PrintWriter cannot directly access the file but must work through the FileWriter class. • The PrintWriter needs a FileWriter object in order to work: FileWriter fwriter = new FileWriter("StudentData.txt"); PrintWriter outputFile = new PrintWriter(fwriter);
The PrintWriter Class • Once linked to the fwriter object, the outputFile object can talk to the file. outputFile.open(); outputFile.println(“Jim”); outputFile.close(); • Just as with the System.out object, the println method of the PrintWriter class will place a newline character after the written data. • The print method can be used to avoid writing the newline character.
Exceptions • When something unexpected happens in a Java program, an exception is thrown. • The method currently executing when the exception is thrown must either handle the exception or pass it up the line. • Handling the exception will be discussed later. • To pass it up the line, the method needs a throws clause in the method header.
Exceptions • To insert a throws clause in a method header, simply add the word throws and the name of the expected exception. • The class Exception can be used to catch all exceptions. public static void main(String[] args) throws IOException{…} • File I/O is a checked exception (meaning the exception must be handled or passed up). • A program with file I/O will generate a compile-time error if the exception is not handled or passed up. • Example:
FileWriteDemo.java • import java.util.Scanner; // Needed for Scanner class • import java.io.*; // Needed for file classes • public class FileWriteDemo • { • public static void main(String[] args) throws IOException • { • String filename; // File name • String friendName; // Friend's name • int numFriends; // Number of friends Scanner keyboard = new Scanner(System.in); • System.out.print("How many friends do you have? "); • numFriends = keyboard.nextInt(); • keyboard.nextLine(); • System.out.print("Enter the filename: "); • filename = keyboard.nextLine();
FileWriteDemo.java • FileWriter fwriter = new FileWriter(filename); • PrintWriter outputFile = new PrintWriter(fwriter); • for (int i = 1; i <= numFriends; i++) • { • // Get the name of a friend. • System.out.print("Enter the name of friend " + • "number " + i + ": "); • friendName = keyboard.nextLine(); • outputFile.println(friendName); • } • outputFile.close(); • System.out.println("Data written to the file."); • } • }
Appending Text to a File • To avoid erasing a file that already exists: • Create a FileWriter object using an optional boolean argument that tells the object to append data to the file. FileWriter fwriter = new FileWriter(“filename”, true); • Data written to a file created in such a manner will be appended to the end of the current file.
Specifying a File LocationWindows’ Crazy Backslash • Windows evolved from DOS. • Since DOS was simply a hacked version of CP/M, it maintained the backslash (\) as a directory separator. • Remember, if the backslash is used in a String literal, it is the escape character so there must be two of them. FileWriter fwriter = new FileWriter("A:\\PriceList.txt"); PrintWriter outputFile = new PrintWriter(fwriter);
Specifying a File Location • This is only necessary if the backslash is in a String literal. • If the backslash is in a String object then it will be handled properly. • Fortunately, Java allows Unix style filenames using the forward slash (/) to separate directories. FileWriter fwriter = new FileWriter("/home/rharrison/names.txt"); PrintWriter outputFile = new PrintWriter(fwriter);
Reading Data From a File • Java provides several classes to read data from a file. • FileReader • Open an existing file for reading and establish a connection with it. • BufferedReader • Uses a buffer to allow the reading of full lines of text at a time rather than one byte at a time.
The FileReader and BufferedReader Classes System.out.print("Enter the filename: "); filename = Keyboard.readString(); FileReader freader = new FileReader(filename); BufferedReader inputFile = new BufferedReader(freader); • The lines above: • Prompt the user for a filename. • Get the filename from the user. • Create an instance of the FileReader class that is associated with the filename. • Create an instance of the BufferedReader class that buffers the instance of the FileReader class.
The FileReader and BufferedReader Classes • Once an instance of BufferedReader is created, lines of text can be read in. customerName = inputFile.readLine(); • A file pointer is created when the file is first opened. • As the file is read, the pointer moves to indicate the text that is to be read next.
Exceptions • The FileReader and BufferedReader classes can throw exceptions. • A throws IOException clause needs to be placed on the method header of the method that instantiates a FileReader or BufferedReader object. • Also, any method that uses a FileReader or BufferedReader needs a throws IOException clause.
Detecting The End of a File • The readLine() method of the BufferedReader class will return null if the end of the file has been reached. FileReader freader = new FileReader(filename); BufferedReader inputFile = new BufferedReader(freader); // Read the first item. String str = inputFile.readLine(); // If an item was read, display it // and read the remaining items. while (str != null) { System.out.println(str); str = inputFile.readLine(); } inputFile.close();// close the file when done.
Open the file Read the first item (priming read) Process the item Did readLine() return null? Read next item Close the file Reading a File Flowchart
FileReadDemo.java • import java.util.Scanner; // Needed for the Scanner class • import java.io.*; // Needed for file classes • public class FileReadDemo • { • public static void main(String[] args) throws IOException • { • String filename; // File name • String friendName; // Friend's name • Scanner keyboard = new Scanner(System.in); • System.out.print("Enter the filename: "); • filename = keyboard.nextLine();
FileReadDemo.java • FileReader freader = new FileReader(filename); • BufferedReader inputFile = new BufferedReader(freader); • friendName = inputFile.readLine(); • while (friendName != null) • { System.out.println(friendName); • friendName = inputFile.readLine(); • } • inputFile.close(); • } • }