340 likes | 541 Views
Input and Output Using Text Files and Exception Handling. Text File I/O and Exception Handling. File Input and Output. Sometimes, we need to save output to use later Retyping test data each time one tests a program is tedious for the user/tester
E N D
Input and Output Using Text Files and Exception Handling Text File I/O and Exception Handling
File Input and Output • Sometimes, we need to save output to use later • Retyping test data each time one tests a program is tedious for the user/tester • Data may be savedto a file so it is only entered once • Files: • May be input files or outputfiles • Must be opened once before they may be used • Data is writtento the file or read from the fileas many times as needed • Must be closedafterlastI/O but before program ends • Starting with Java 7, one is required to close a keyboard scannerobject after the last input operation (e.g., kb.close( );)
Types of Files in Java • In general, there are two types of files: • Binary • Text – this is the only type we consider at this point • Text files contain ordinary, humanly readable text • Similar to program output displayed in a console window • Stored in a file on a hard disk, on a removable disk, burned to a CD/DVD, stored on a USBdrive, or other storage medium • It is notautomatically displayed on the screen
Text Files • Text files are humanly readable • Textfiles may be created by • A program such as a Java program you write • A texteditor such as Notepad, Notepad++, or the Eclipse editor • Other types of programs as well • Existing textfiles by also be opened and read using • A texteditor such as Notepad or Notepad++ • A Javaprogram • Other software • Textfiles usually have an extension of .txt, but they may have others as well
Delimited Text Files • Plain text files contain ordinary text that one can read • If the text contains “fields” such as a name, address, phone number, email address, and so forth, it is often useful to separatethefields with a character that otherwise does not appear in the text. This allows the reader to tell where one field ends and the next begins. • This separatorcharacter is called a delimiter • Must only be a singlecharacter such as , ; | # ^ $ • Must not appear anywhere else in the file • For example, if the data in the text file contains a name such as Badly, Claude in which the comma appears as part of the name, the comma cannot be the delimiter character
Text File Example This is an example of a “|-delimited” file. The individual fields are separated by some character that is not found anywhere in the data. In this case, that is the “|” character. Screen snapshot taken from a text editor such as Notepad++
File Choosers • A file chooseris a specialized dialogbox that allows the user to browse for a file and select it as below
File Choosers • Create an instance of the JFileChooser class to display a file chooser dialog box • Two of the constructors have the form: JFileChooser ( ) JFileChooser (String path) • First constructor shown takes no arguments; uses the defaultdirectory (typically Documents on Windows) as the starting point for all of its dialog boxes • The second constructor takes a String argument containing a valid path. This path will be the starting point for the object’s dialog boxes • This may be a Stringvariable • Try to NEVER use an absolute path as the program may not work on another computer
File Choosers • AJFileChooser object can display two types of predefined dialog boxes: • openfile dialog box – lets the user browse for an existing file to open • a save file dialog box – lets the user browse to a folder (directory) to save a file
File Choosers • To display an open file dialog box, use the showOpenDialogmethod • General format: intshowOpenDialog(Component parent) • The argument can be null or a referencetoacomponent • If null is passed, the dialog box is normally centered in the screen • If you pass a reference to a component the dialog box is displayed over the component
File Choosers • To display a save file dialog box, use the showSaveDialogmethod • General format: intshowSaveDialog(Component parent) • The argument can be either null or a reference to a component • Both methods return an integer that indicates what action was takenby the user to close the dialog box (OKor Cancel)
File Choosers • You can compare the return value to one of the following constants: • JFileChooser.CANCEL_OPTION – indicates that the user clicked on the Cancel button • JFileChooser.APPROVE_OPTION – indicates that the user clicked on theOKbutton • JFileChooser.ERROR_OPTION – indicates that an error occurred, or the user clicked on the standard close button on the window to dismiss it • If the user selected a file, use the getSelectedFile method to determine the file that was selected • The getSelectedFile method returns a File object, which contains data about the selected file
File Choosers • Use the File object’s getPath method to get the path and file name as a String JFileChooser fileChooser = new JFileChooser ( ); int status = fileChooser.showOpenDialog (null); if (status == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile ( ); Scanner input = new Scanner(selectedFile); // Now we can input from this file in standard way }
Selecting a file to open/process Dialog Caption Filter – show only .txt files In project but in different folder than .src
Writing Text To a File • To open a file for textoutput you create an instance of the PrintWriterclass This may come from the JFileChooser results Refer to the file by this name in the rest of the program PrintWriter outputFile = new PrintWriter("StudentData.txt"); Pass thename of the filethat you wish to open as a stringargumentto thePrintWriterconstructor. Warning If the output filealreadyexists, it will beerasedandreplacedwith anewfile.
The PrintWriter Class • The PrintWriter class allows you to writedatatoa file using the print and println methods, similar to the way you use them to display data on the screen with the System.out object • Just as with the System.out object, the println method of the PrintWriter class will place a newlinecharacterafter the written data • The print method writes data without writing the newlinecharacter
The PrintWriter Class Create and Open the PrintWriter file object PrintWriter outFile = new PrintWriter (“Data/Names.txt"); outFile.println (“Andria"); outFile.println (“Scottie"); outFile.println (“Benjamin"); outFile.close ( ); Names.txt is in subfolder named Data – this could be the results from using JFileChooser Close the file object Write data to the file
The PrintWriter Class • To use the PrintWriter class, put the following import statement at the top of the source file: importjava.io.*; • See example: FileWriteDemo.java
Exceptions • As we have seen, when some unexpected problem occurs in a Java program, an exception is thrown • The method that is executing when the exception is thrown must either handletheexception or passitup the line • To pass the exception up the line, the method needs a throws clause in the methodheader • This is only needed if the method does not provide its own catch-handler
Exceptions • To insert a throws clause in a methodheader, simply add the word throws and the type of the potential exception • PrintWriter objects can throw an IOException, so we write the throws clause like this: public static void main (String[ ] args)throws IOException
Appending Text to a File • To avoid erasing a file that already exists, create a FileWriter object in this manner:FileWriter fw = new FileWriter("names.txt",true); • Then, create a PrintWriter object in this manner:PrintWriter outFile = new PrintWriter(fw); Thetrueparameter indicates this data should be added to the end of the existing file rather than replacing the data already there.
Specifying a File Location • In Windows, pathsmay contain backslash (\) characters to separate a drive or parent folder name from what follows as in C:\temp\nutsbolts.txt • Remember, in Java, if the backslash is used in a string literal, it is the escapecharacter. • You must use twobackslashes to indicate that a single backslash is a part of the value rather than an escape character: PrintWriter outFile = new PrintWriter (“C:\\nature.txt");
Specifying a File Location • This is only necessary if the backslash is in a stringliteral • If the backslash is in a String object then it will be handled properly • This would be the case if the user types the file path and file name in response to a prompt • Java also allows Unixstylefilenames using the forwardslash (/) to separate folder names: PrintWriter outFile = new PrintWriter("/home/myfiles/names.txt");
File Output Example Creates an output file named ContactList.txt in the ContactData subfolder and fills it with information (Contact objects) from addressBook. The fields in a Contact are delimited by pipe characters (“|”).
Reading Data From a File • You use the File class and the Scanner class to readdata from a file: Pass the name of the file as an argument to the File class constructor. The name may have come from the results of JFileChooser File myFile = new File("Customers.txt"); Scanner inputFile = new Scanner(myFile); Pass the File object as an argument to the Scanner class constructor.
Reading Data From a File Scanner keyboard = new Scanner (System.in); System.out.print ("Enter the filename: "); String fileName = keyboard.nextLine ( ); File file = new File (fileName); Scanner inputFile = new Scanner (file); • The lines above: • Create an instance of the Scanner class to read from the keyboard • Prompt the user for a fileName • Get the fileNamefrom the user • Create an instance of the File class to represent the file • Create an instance of the Scanner class that reads from the file • Note that there are two Scanner objects – one to input from the keyboard and another to input from a disk file
Reading Data From a File • Once an instance of Scanner is created for a file, data can be read using the same methods that you have used to read keyboard input (nextLine, nextInt, nextDouble, etc). • // Open the file • File file = new File("Names.txt"); • Scanner inputFile = new Scanner(file); • // Read a line from the file • String str = inputFile.nextLine( ); • // Close the file • inputFile.close( );
Exceptions • The Scanner class may throw an IOException when a File object is passed to its constructor if there is a problem accessing the file • So, we mustdo at least one of the following twothings: • We handle the potential exception ourselves • We put a throwsIOExceptionclause in the headerofthemethod that instantiates the Scannerclass • See Example: ReadFirstLine.java
Example throws clause example We could do this line in a loop to input more than one line from file
Detecting The End of a File • The Scanner class’s hasNext( )method returns trueif another item can be read from the file // Open the file File file = new File(filename); Scanner inputFile = new Scanner(file); // Read until the end of the file is reached while (inputFile.hasNext( )) { String str = inputFile.nextLine( ); System.out.println(str); } inputFile.close();// close the file when done
Handling an Exception • Example: Try to open input file – exception thrown if unsuccessful Terminate the pgm
Example, continued File is in subfolder named ContactData While there is more data The \\ are needed because the | is must be “escaped” in the split method Fields separated by “|”
Data for the previous method The fields are separated by the pipe character (“|”) to make it easy to determine where one field ends and the next begins