A Summary of File IO Writing

advertisement
A Summary of File IO
There are classes that can be used to read and write files.
Writing
 PrintWriter class
 possibly using the FileWriter class
Consider the following example which uses PrintWriter:
PrintWriter outFile = new PrintWriter(“Sourcefile.txt”);
In this example the file name is coded into the program and can’t be changed or entered by the user.
Consider the following alternative:
String filename;
filename = JOptionPane.showInputDialog(“Enter the filename: “);
PrintWriter outFile = new PrintWriter(filename);
WARNING: If you open a file using PrintWriter in this way, and that file already exists, it will be erased,
and you will start with a blank file.
Now look at writing using the FileWriter class.
String filename;
filename = JOptionPane.showInputDialog(“Enter the filename: “);
FileWriter fwriter = new FileWriter(filename, true);
PrintWriter outFile = new PrintWriter(fwriter);
The presence of the primitive type true in the instantiation of the fwriter object in the class
FileWriter, means that writing to this file will begin at the end of the current file. That is, if the file
exists, it will append new output to it, and not overwrite the current file.
Reading
 Scanner class and
 File class
To read a file, first instantiate a File object associated with the file to be read, and then instantiate a
Scanner object associated with File object previously opened. Consider the following code:
String filename;
filename = JOptionPane.showInputDialog(“Enter file to read: “);
File myFile = new File(filename);
Scanner inputFile = new Scanner(myFile);
Note that when opening the Scanner object, myFile is taking the place of System.in, which was
previously used when we did standard input from the keyboard.
A file opened for reading or writing should be closed when the program no longer will access it.
NOTE: This is a beginning process. We aren’t saying anything yet about exceptions thrown when an
input error occurs.
Download