35
TEXT FILE I/O AND EXCEPTION HANDLING Input and Output Using Text Files and Exception Handling

Input and Output Using Text Files and Exception Handling

Embed Size (px)

Citation preview

Page 1: Input and Output Using Text Files and Exception Handling

TEXT FILE I/O AND EXCEPTION HANDLING

Input and Output Using Text Files and Exception Handling

Page 2: Input and Output Using Text Files and Exception Handling

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

Data may be saved to a file so it is only entered once

In practice, we frequently need to save information semi-permanentlyHealth recordsStudent transcriptsLegal recordsEmployee recordsAnd so forth . . .

Page 3: Input and Output Using Text Files and Exception Handling

FilesFiles:

May be input files or output filesMust be opened once before they may be usedData is written to the file or read from the file as

many times as neededMust be closed after last I/O but before program ends

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 ( );

Page 4: Input and Output Using Text Files and Exception Handling

Types of Files in Java

In general, there are two types of files:Binary – data stored in “computerized” formatText – this is the only type we consider at this point

Text files contain ordinary, humanly readable textSimilar to program output displayed in a console windowStored 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

It is not automatically displayed on the screen

Page 5: Input and Output Using Text Files and Exception Handling

Text FilesText files are humanly readableText files may be created by

A program such as a Java program you write A text editor such as Notepad, Notepad++, or the Eclipse editorOther types of programs as well

Existing text files by also be opened and read using A text editor such as Notepad or Notepad++A Java programOther software

Text files usually have an extension of .txt, but they may have others as well

5-5

Page 6: Input and Output Using Text Files and Exception Handling

Delimited Text FilesPlain 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 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.

This separator character is called a delimiter Must only be a single character 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

Page 7: Input and Output Using Text Files and Exception Handling

Text File ExampleScreen

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.

Page 8: Input and Output Using Text Files and Exception Handling

12-8

File ChoosersA file chooser is a specialized dialog box that allows

the user to browse for a file and select it as below

Page 9: Input and Output Using Text Files and Exception Handling

12-9

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 default directory (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 String variable

Try to NEVER use an absolute path as the program may not work on another computer

Page 10: Input and Output Using Text Files and Exception Handling

12-10

File Choosers

A JFileChooser object can display two types of predefined dialog boxes:

open file 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

Page 11: Input and Output Using Text Files and Exception Handling

12-11

File ChoosersTo display an open file dialog box, use the showOpenDialog method

General format:

int showOpenDialog (Component parent)

The argument can be null or a reference to a component

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

Page 12: Input and Output Using Text Files and Exception Handling

12-12

File ChoosersTo display a save file dialog box, use the showSaveDialog method

General format:

int showSaveDialog (Component parent)

The argument can be either null or a reference to a component

Both “show” methods return an integer that indicates what action was taken by the user to close the dialog box (Open or Cancel)

Page 13: Input and Output Using Text Files and Exception Handling

12-13

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 the OK button

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 which file that was selected

The getSelectedFile method returns a File object, which contains data about the selected file

Page 14: Input and Output Using Text Files and Exception Handling

12-14

File ChoosersUse the File object’s getPath method to

get the path and file name as a StringJFileChooser 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

}

Page 15: Input and Output Using Text Files and Exception Handling

Selecting a file to open/process

Filter – show

only .txt and .text

files

Dialog Captio

n

In project but in

different folder

than src

Page 16: Input and Output Using Text Files and Exception Handling

5-16

Writing Text To a FileTo open a file for text output you create

an instance of the PrintWriter class

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

Page 17: Input and Output Using Text Files and Exception Handling

5-17

The PrintWriter ClassThe 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

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 writes data without writing the newline character

Page 18: Input and Output Using Text Files and Exception Handling

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

Page 19: Input and Output Using Text Files and Exception Handling

5-19

The PrintWriter ClassTo use the PrintWriter class, put the

following import statement at the top of the source file:

import java.io.*;

See example: FileWriteDemo.java

Page 20: Input and Output Using Text Files and Exception Handling

Output File Demo

Page 21: Input and Output Using Text Files and Exception Handling

5-21

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 handle the exception or pass it up the line

To pass the exception up the line, the method needs a throws clause in the method headerThis is only needed if the method does not

provide its own catch-handler

Page 22: Input and Output Using Text Files and Exception Handling

5-22

Exceptions

To insert a throws clause in a method header, 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

Page 23: Input and Output Using Text Files and Exception Handling

5-23

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);The true parameter indicates this data should

be added to the end of the existing file rather than replacing the data

already there.

Page 24: Input and Output Using Text Files and Exception Handling

5-24

Specifying a File LocationIn Windows, paths may 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 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");

Page 25: Input and Output Using Text Files and Exception Handling

5-25

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 properlyThis would be the case if the user types the

file path and file name in response to a prompt

Java also allows Unix style filenames using the forward slash (/) to separate folder names:PrintWriter outFile = new PrintWriter("/home/myfiles/names.txt");

Page 26: Input and Output Using Text Files and Exception Handling

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

Page 27: Input and Output Using Text Files and Exception Handling

5-27

Reading Data From a File

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);

Pass the name of the file as an argument to

the File class constructor. The name

may have come from the results of JFileChooser

Pass the File object as an argument to the

Scanner class constructor

Page 28: Input and Output Using Text Files and Exception Handling

5-28

Reading Data From a FileScanner 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 fileName from 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

Page 29: Input and Output Using Text Files and Exception Handling

5-29

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 fileFile file = new File("Names.txt");Scanner inputFile = new Scanner(file);

// Read a line from the fileString str = inputFile.nextLine( );

// Close the fileinputFile.close( );

Page 30: Input and Output Using Text Files and Exception Handling

5-30

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 must do one of the following two things:We handle the potential exception ourselves

We put a throws IOException clause in the header of the method that instantiates the Scanner class

See Example: ReadFirstLine.java

Page 31: Input and Output Using Text Files and Exception Handling

Examplethrows clause

example

We could do this line in a loop to input more than one line from file

Page 32: Input and Output Using Text Files and Exception Handling

5-32

Detecting The End of a FileThe Scanner class’s hasNext( ) method returns true if another item can be read from the file

// Open the fileFile file = new File(filename);Scanner inputFile = new Scanner(file);

// Read until the end of the file is reachedwhile (inputFile.hasNext( )){ String str = inputFile.nextLine( ); System.out.println(str);}

inputFile.close();// close the file when done

Page 33: Input and Output Using Text Files and Exception Handling

5-33

Handling an Exception

Example:

Try to open input file – exception

thrown if unsuccessful

Terminate the pgm

Page 34: Input and Output Using Text Files and Exception Handling

Example, continued

While there is more data

Fields separated by

“|”

File is in subfolder

named ContactData

The \\ are

needed because the | is

must be “escape

d” in the split method

Page 35: Input and Output Using Text Files and Exception Handling

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