Presentation is loading. Please wait.

Presentation is loading. Please wait.

Input and Output Using Text Files and Exception Handling.

Similar presentations


Presentation on theme: "Input and Output Using Text Files and Exception Handling."— Presentation transcript:

1 Input and Output Using Text Files and Exception Handling

2 5-2 File Input and Output  Sometimes, we need to save program results to use later  Retyping test data each time one tests a program is tedious for the user/tester savedto a file  Data may be saved to a file so it is only entered once  In practice, we frequently need to save information semi-permanently  Health records  Student transcripts  Legal records  Employee records  And so forth...

3 Files  Files: input filesoutput files  May be input files or output files opened  Must be opened once before they may be used writtenfilereadfile  Data is written to the file or read from the file as many times as needed closedafterlast I/O  Must be closed after last I/O but before program ends keyboard scannerobject  Starting with Java 7, one is required to close a keyboard scanner object after the last input operation to avoid a warning message. For example: kb.close ( );

4 Types of Files in Java two types of files  In general, there are two types of files:  Binary – data stored in “computerized” format  Text – this is the only type we consider at this point  Text files  Text files contain ordinary, humanly readable text  Similar to program output displayed in a console window hard diskdisk CD/DVDUSBdrive  Stored in a file on a hard disk, on a removable disk, burned to a CD/DVD, stored on a USB drive, or other storage medium notdisplayed  It is not automatically displayed on the screen

5 Text Files  Text files  Text files are humanly readable  Textfilescreated  Text files may be created by programJava program  A program such as a Java program you write texteditorNotepadNotepad++, Eclipse  A text editor such as Notepad, Notepad++, or the Eclipse editor  Other types of programs as well textfilesopenedread  Existing text files by also be opened and read using text editorNotepadNotepad++  A text editor such as Notepad or Notepad++ Javaprogram  A Java program  Other software  Textfiles.txt  Text files usually have an extension of.txt, but they may have others as well 5-5

6 Delimited Text Files  Plain text files contain ordinary text that one can read fields separatethefields  If the text contains “fields” such as a name, address, phone number, email address, and so forth, it is often useful to separate the fields with some character that otherwise does not appear in the text. This allows the reader to tell where one field ends and the next begins. separatorcharacterdelimiter  This separator character is called a delimiter singlecharacter, ; | # ^ $  Must only be a single character such as, ; | # ^ $  Must not appear anywhere else in the file comma  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

7 Text File Example Screen snapshot taken from a text editor such as Notepad++ 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.

8 12-8 File Choosers file chooser dialog box  A file chooser is a specialized dialog box that allows the user to browse for a file and select it as below

9 12-9 File Choosers JFileChooser  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) defaultdirectoryDocuments Windows  First constructor shown takes no arguments; uses the default directory (typically Documents on Windows ) as the starting point for all of its dialog boxes String  The second constructor takes a String argument containing a valid path. This path will be the starting point for the object’s dialog boxes String  This may be a String variable  Try to NEVER use an absolute path as the program may not work on another computer

10 12-10 File Choosers  A JFileChooser  A JFileChooser object can display two types of predefined dialog boxes:  openfile  open file dialog box – lets the user browse for an existing file to open save file  a save file dialog box – lets the user browse to a folder (directory) to save a file

11 12-11 File Choosers open file showOpenDialog  To display an open file dialog box, use the showOpenDialog method  General format: int showOpenDialog (Component parent) nullreference to a component  The argument can be null or a reference to a component null centered in the screen  If null is passed, the dialog box is normally centered in the screen reference to a component displayed over the component  If you pass a reference to a component the dialog box is displayed over the component

12 12-12 File Choosers save file showSaveDialog  To display a save file dialog box, use the showSaveDialog method  General format: int showSaveDialog (Component parent) null reference to a component  The argument can be either null or a reference to a component integer action was takenuser close the dialog box (Open Cancel)  Both “show” methods return an integer that indicates what action was taken by the user to close the dialog box (Open or Cancel)

13 12-13 File Choosers  You can compare the return value to one of the following constants:  JFileChooser.CANCEL_OPTION  JFileChooser.CANCEL_OPTION – indicates that the user clicked on the Cancel button  JFileChooser.APPROVE_OPTION OK  JFileChooser.APPROVE_OPTION – indicates that the user clicked on the OK button  JFileChooser.ERROR_OPTION  JFileChooser.ERROR_OPTION – indicates that an error occurred, or the user clicked on the standard close button on the window to dismiss it getSelectedFile  If the user selected a file, use the getSelectedFile method to determine which file that was selected getSelectedFileFile  The getSelectedFile method returns a File object, which contains data about the selected file

14 12-14 File Choosers FilegetPath String  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 }

15 Selecting a file to open/process Filter – show only.txt and.text files Dialog Caption In project but in different folder than src

16 5-16 Writing Text To a File opentextoutput PrintWriter  To open a file for text output you create an instance of the PrintWriter class PrintWriter outputFile = new PrintWriter("StudentData.txt"); PrintWriter outputFile = new PrintWriter("StudentData.txt"); Pass the name of the file that you wish to open as a string argument to the PrintWriter constructor. Warning! If the output file already exists, it will be erased and replaced with a new file. Refer to the file by this name in the rest of the program This may come from the JFileChooser results instead of being “hard-coded” here

17 5-17 The PrintWriter Class PrintWriterwrite data to a fileprint println System.out  The PrintWriter class allows you to write data to a 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 System.out printlnPrintWriter newline character  Just as with the System.out object, the println method of the PrintWriter class will place a newline character after the written data printwithout newline  The print method writes data without writing the newline character

18 5-18 The PrintWriter Class PrintWriter outFile = new PrintWriter (“Data/Names.txt"); outFile.println (“Brandon"); outFile.println (“Fred"); outFile.println (“Emily"); outFile.close ( ); Create and Open the PrintWriter file object Write data to the file Close the file object Names.txt is in subfolder named Data – this could be the results from using JFileChooser

19 5-19 The PrintWriter Class PrintWriter import  To use the PrintWriter class, put the following import statement at the top of the source file: import java.io.*;  See example: FileWriteDemo.javaFileWriteDemo.java

20 Output File Demo

21 5-21 Exceptions exceptionthrown  As we have seen, when some unexpected problem occurs in a Java program, an exception is thrown methodexception thrownhandle the exceptionpass it up the line  The method that is executing when the exception is thrown must either handle the exception or pass it up the line method throwsmethodheader  To pass the exception up the line, the method needs a throws clause in the method header only  This is only needed if the method does not provide its own catch-handler

22 5-22 Exceptions throwsmethodheader throws exception  To insert a throws clause in a method header, simply add the word throws and the type of the potential exception  PrintWriter IOExceptionthrows  PrintWriter objects can throw an IOException, so we write the throws clause like this: public static void main (String[ ] args) throws IOException

23 5-23 Appending Appending Text to a File FileWriter FileWriter fw = new FileWriter("names.txt", true);  To avoid erasing a file that already exists, create a FileWriter object in this manner: FileWriter fw = new FileWriter("names.txt", true); PrintWriter PrintWriter outFile = new PrintWriter(fw);  Then, create a PrintWriter object in this manner: PrintWriter outFile = new PrintWriter(fw); The true parameter indicates this data should be added to the end of the existing file rather than replacing the data already there.

24 5-24 Specifying a File Location Windowspathsbackslash\  In Windows, paths may contain backslash (\) characters to separate a drive or parent folder name from what follows as in C:\temp\nutsbolts.txt backslash escapecharacter  Remember, in Java, if the backslash is used in a string literal, it is the escape character two backslashes backslashpart of the value escape character  You must use two backslashes to indicate that a single backslash is a part of the value rather than an escape character: PrintWriter outFile = new PrintWriter (“C: \\ nature.txt");

25 5-25 Specifying a File Location backslashstring literal  This is only necessary if the backslash is in a string literal String  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  JavaUnixstylefilenames forwardslash/  Java also allows Unix style filenames using the forward slash (/) to separate folder names: PrintWriter outFile = new PrintWriter("/home/myfiles/names.txt"); PrintWriter("/home/myfiles/names.txt");

26 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 (“|”).

27 5-27 Reading Data From a File FileScanner readdata  You use the File class and the Scanner class to read data from a file: File myFile = new File("Customers.txt"); Scanner inputFile = new Scanner(myFile); name of the file argumentFile JFileChooser 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 argumentScanner Pass the File object as an argument to the Scanner class constructor

28 5-28 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: Scannerkeyboard  Create an instance of the Scanner class to read from the keyboard fileName  Prompt the user for a fileName fileName  Get the fileName from the user Filefile  Create an instance of the File class to represent the file Scanner  Create an instance of the Scanner class that reads from the file Scanner  Note that there are two Scanner objects – one to input from the keyboard and another to input from a disk file

29 5-29 Reading Data From a File Scanner keyboardnextLinenextIntnextDouble  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"); ScannerinputFile = new Scanner(file); // Read a line from the file String str = inputFile.nextLine( ); // Close the file inputFile.close( );

30 5-30 Exceptions ScannerIOException File  The Scanner class may throw an IOException when a File object is passed to its constructor if there is a problem accessing the file mustdoonetwo things  So, we must do one of the following two things :  We handle the potential exception ourselves throws IOException headerof the method Scanner  We put a throws IOException clause in the header of the method that instantiates the Scanner class  See Example: ReadFirstLine.javaReadFirstLine.java

31 Example throws clause example We could do this line in a loop to input more than one line from file

32 5-32 Detecting The End of a File ScannerhasNext( ) true  The Scanner class’s hasNext( ) method returns true if 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 () while ( inputFile.hasNext( ) ){ String str = inputFile.nextLine( ); String str = inputFile.nextLine( ); System.out.println(str); System.out.println(str);} // close the file when done inputFile.close();// close the file when done

33 5-33 Handling an Exception  Example: Try to open input file – exception thrown if unsuccessful Terminate the pgm

34 Example, continued While there is more data Fields separated by “|” File is in subfolder named ContactData The \\ are needed because the | is must be “escaped” in the split method

35 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


Download ppt "Input and Output Using Text Files and Exception Handling."

Similar presentations


Ads by Google