You are on page 1of 93

Chapter 4 LOOPS AND FILES

LOOPS
The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds of loops: the while loop, the do-while loop, and the for loop.

THE while LOOP


The while loop/statement has the form:
while (Boolean expression) { statement(s); }
This is the loop header. The statement(s) that are to be repeatedly executed are the body of the loop.

The while(Boolean expression) is the loop header. It consists of the keyword while and a parenthesized boolean expression, often called the loop continuation expression. The body of the loop follows the header. The body of the loop is the statement or block of statements that are to be repeated as long as the loop continuation expression evaluates to true.
3

THE while LOOP


while (Boolean expression) { statement(s); }
Dont put a semicolon here. The header is only the beginning of the while statement.

The braces are not necessary if the body of the loop is a single statement. Notice that there is no semicolon after the loop continuation expression. A complete while statement includes a loop header and the loop body.

THE while LOOP


It is considered good programming style to begin the body of the loop on the line below the continuation expression and indent the statement(s) that make up the body of the loop one level from the keyword while.
while (Boolean expression) { statement(s); }

THE while LOOP


while (Boolean expression) { statement(s); }

When execution reaches a while statement, the parenthesized loop continuation expression is evaluated, if the expression is true the statement(s) that make up the body are executed and then execution returns to the evaluation of the continuation expression. This process is repeated until the loop continuation expression is evaluated and has the value false. When this happens execution continues with the statement following the while statement.
6

THE while LOOP


The loop continuation expression must eventually become false or an infinite loop results. An infinite loop is a loop that does not have a way to terminate normally.
while (Boolean expression) { statement(s); }

THE while LOOP


while (Boolean expression) { statement(s); }

One repetition of the body of a loop is called an iteration. The while loop is a pretest loop. The continuation expression is tested before the body of the loop is executed. If the continuation expression is false on the initial test, the body of the loop is never executed, i.e. it never iterates.

THE while LOOP


Flow Chart Representation of a Pretest Loop

False

Continuation expression ? True

Statement(s)

THE while LOOP


/** This program demonstrates the while loop. It is equivalent to WhileLoop.java from the text. */ public class WhileLoop { public static void main(String [ ] args) { int number = 1; while (number <= 5) { System.out.println("Hello"); number += 1; } System.out.println("That's all!"); System.exit(0); } }

10

THE do-while LOOP


The do-while loop/statement has the form:
do { statement(s); } while (Boolean expression);
Notice there is a semicolon here, because this is the end of the do-while statement.

The key word do is followed by the body of the loop, the key word while, the parenthesized loop continuation expression, and a semicolon. The braces are not necessary if the body of the loop is a single statement.
11

THE do-while LOOP


It is considered good programming style to begin the body of the loop on the line below the key word do and indent the statements that make up the body one level from the key word do. The key word while and the continuation expression should be on the line following the loop body and be at the same level of indentation as the key word do.
do { statement(s); } while (Boolean expression);

12

THE do-while LOOP


do { statement(s); } while (Boolean expression);

When execution reaches a do-while statement, the statement or block of statements that make up the body of the loop are executed and then the continuation expression is evaluated. If the continuation expression evaluates to true execution continues at the first statement of the loop body. This process is repeated until the evaluation of the continuation expression results in the value false. When the continuation expression evaluates to false, execution continues with the first statement following the do-while statement. 13

THE do-while LOOP


do { statement(s); } while (Boolean expression);

The do-while loop is a posttest loop. The test expression is evaluated at the end of an iteration of the loop body. The body of the do-while loop is executed at least once.

14

THE do-while LOOP


Flowchart Representation of a Posttest Loop

Statement(s)

Continuation expression ? False

True

15

*** See the program TotalScore.java which is available on webct.


The variables totalGoalsTeam1 and totalGoalsTeam2 are accumulators. An accumulator is a variable used to store a running total that accumulates over the iterations of the loop. An accumulator must be given a starting value before the loop begins to iterate. In our program, the accumulators, totalGoalsTeam1 and totalGoalsTeam2, are assigned the value zero before the loop is entered. The first period goals of team1 are added to totalGoalsTeam1, the second period goals of team1 are added to the goals scored in the first period, and the third period goals are added to the sum of the first and second period goals. Similarly, we accumulate the goals of team2 in totalGoalsTeam2. After all the iterations of the loop we have the total goals of team1 in totalGoalsTeam1 and the total goals of team2 in totalGoalsTeam2.
16

THE for LOOP


The for loop/statement has the form:
for(initialization; Boolean expression; update) { statement(s); }

The for(initialization; Boolean expression; update) is the loop header. It consists of the key word for followed by three parenthesized expressions separated by semicolons. Notice there is not a semicolon after the third expression, the update.

17

THE for LOOP


for(initialization; Boolean expression; update) { statement(s); }

The first expression is the initialization expression. It is typically used to initialize a counter, accumulator, or other variable that must be given a starting value. This is the first action performed by the loop and it is only done once.

18

THE for LOOP


for(initialization; Boolean expression; update) { statement(s); }

The second expression is the loop continuation expression. This is a boolean expression that gets evaluated before every iteration of the loop to determine if the loop should iterate. If the continuation expression is true the statement(s) that make up the body of the loop are executed.

19

THE for LOOP


for(initialization; Boolean expression; update) { statement(s); }

The third expression is the update expression. It is executed at the end of each iteration before execution returns to the continuation expression. Typically, this is a statement that updates the value of a variable that is used to control the loop.

20

THE for LOOP


for(initialization; Boolean expression; update) { statement(s); }

There is no semicolon here. A complete for statement includes the statement(s) to be repeatedly executed.

The statement(s) in the loop body are to be repeated as long as the continuation expression evaluates to true. The braces are not necessary if the body of the loop is a single statement. Notice that there is no semicolon after the parenthesized expressions. A complete for loop/statement includes the loop body.

21

THE for LOOP


It is considered good programming style to begin the body of the loop on the line below the parenthesized expressions and indent the statements that make up the body of the loop one level from the key word for.
for(initialization; Boolean expression; update) { statement(s); }

22

THE for LOOP


for(initialization; Boolean expression; update) { statement(s); }

The for loop is a pretest loop. If the continuation expression evaluates to false on the initial test, the body of the loop does not iterate.

23

THE for LOOP


Flow Chart Representation of a for Loop
Initialization

False

Continuation expression ? True

Statement(s)

Update

24

THE for LOOP


/* A program to demo a for loop. This program displays the first 10 even integers greater than 0. Source filename: DisplayEven.java By: L. Thompson */ public class DisplayEven { public static void main(String[ ] args) { int count, number; number = 2; for(count = 1; count <= 10; count += 1) { System.out.print(number + " "); number += 2; } System.out.println( ); System.exit(0); } } Create using: jGRASP

25

THE for LOOP


The variable count in the program DisplayEven.java is a counter. A counter is a variable that is used to keep track of, or control, the number of times a task is performed, or a loop iterates.

26

THE INCREMENT AND DECREMENT OPERATORS


To increment a variable means to increase its value by one. To decrement a variable means to decrease its value by one. To accomplish these tasks we could write statements like:
a = a + 1; b = b 1;

or
a += 1; b = 1;
27

THE INCREMENT AND DECREMENT OPERATORS


These operations are so common in computer applications that Java offers special operators that can be used to specify these operations more concisely. The increment operator (++) is a unary operator that increases the value of the variable that is its operand by one. The decrement operator (--) is a unary operator that decreases the value of the variable that is its operand by one.

28

THE INCREMENT AND DECREMENT OPERATORS


To increase the value in the variable a by one we can write:
a++;

To decrease the value in the variable b by one we can write:


b--;

29

THE INCREMENT AND DECREMENT OPERATORS


The operand of the increment or decrement operator must be a variable (must have a lvalue must correspond to a location in memory whose contents may be changed).
Examples: 5--; // This is an error 5 does not have an lvalue // We cannot write 5 = 5 1 // This is an error a + b does not have an lvalue // We cannot write a + b = a + b + 1

(a + b)++;

30

POSTFIX AND PREFIX MODES OF THE INCREMENT AND DECREMENT OPERATORS


The increment and decrement operators can appear after their operand, which is the postfix mode. The postfix mode specifies that the increment or decrement is to occur after the variable is used in the expression. The increment and decrement operators can appear before their operand, which is the prefix mode. The prefix mode specifies that the increment or decrement is to occur before the variable is used in the expression. If you use the increment and decrement operators in simple statements that perform only the increment and decrement operation it does not matter if you use the prefix or the postfix mode of the operators.
31

POSTFIX AND PREFIX MODES OF THE INCREMENT AND DECREMENT OPERATORS


int x = 5, y = 10; x++; --y; System.out.println("x is " + x); System.out.println("y is " + y);

Output:
x is 6 y is 9

32

POSTFIX AND PREFIX MODES OF THE INCREMENT AND DECREMENT OPERATORS


If you use the increment and decrement operators in more complex expressions, the use of the prefix or postfix mode is significant.
The second statement of the segment below specifies that the value of a is to be copied into the variable b and then a is to be incremented.
int a = 10, b; b = a++; System.out.println("a is " + a + " and b is " + b);

Output:
a is 11 and b is 10
33

POSTFIX AND PREFIX MODES OF THE INCREMENT AND DECREMENT OPERATORS


The if/else statement below specifies that the variable c is to be decremented and then its value is to be tested to see if it is greater than or equal to 10. If the new value of c is greater than or equal to 10, the message c is greater than or equal to 10 is to be displayed, otherwise, the message c is less than 10 is to be displayed.
int c = 10; if(--c >= 10) { System.out.println("c is greater than or equal to 10."); } else { System.out.println("c is less than 10."); }
34

POSTFIX AND PREFIX MODES OF THE INCREMENT AND DECREMENT OPERATORS


The if/else statement below specifies that the variable c is to be to tested to see if it is greater than or equal to 10 and then it is to be decremented. If the value of c before the decrement is greater than or equal to 10, the message c is greater than or equal to 10 is to be displayed, otherwise, the message c is less than 10 is to be displayed.
int c = 10; if(c-- >= 10) { System.out.println("c is greater than or equal to 10."); } else { System.out.println("c is less than 10."); }

35

Problem: Write a pseudocode algorithm for a program that gets fifty grades from the user and calculates and displays the average of the grades entered. You may assume that the grades entered will all be whole numbers.
Set total to 0 For count of grades 1 through 50 Get the grade Add the grade to the total Calculate the average grade by dividing total by 50 Display the average grade

36

*** See the program AvgOf50Grades.java on webct

37

OTHER FORMS OF THE UPDATE EXPRESSION


The update of a loop counter does not have to be ++. There are some situations where it is more natural to count backwards so we might initialize a counter to a value at the top end of a range and decrease its value by using --. We might want to count upward or downward by some value other than one so we might use the += or the -= operator for our update.

*** See Other Forms of the Update Expression in Section 4.5 of the text *** See Checkpoint questions 4.9c, 4.11, & 4.12 on pages 198199 of the text
38

COUNT_CONTROLLED LOOPS
All of the loops we have looked at so far are count-controlled loops. A count-controlled loop is a loop that executes a specified number of times. When you construct a count-controlled loop you need to: 1. Give the counter a starting value. 2. Compare the counter to a maximum (or minimum) value in the loop continuation expression. When the counter reaches this value the loop terminates. 3. Update the value of counter. Review the programs and see if you can figure out which variable is the counter and see how the three actions above were 39 done.

COUNT_CONTROLLED LOOPS VS. CONDITIONAL LOOPS


A count-controlled loop is one type of loop. You can write this kind of loop when you know the exact number of times the loop needs to iterate. If you dont know how many times a loop needs to iterate, you can write a conditional loop. A conditional loop iterates as long as some condition exists. For example, a user controlled loop might iterate as long as a user enters a value signaling that he/she wants to keep going or it might iterate as long as the user doesnt enter a value indicating that he/she wants to stop. An input validation loop usually continues to iterate as long as invalid data is entered. A loop might continue to iterate as long as there is more data in a file that needs to be processed. Etc.
40

SENTINEL-CONTROLLED LOOPS

Suppose we did not know the number of grades that were to be entered in our application to calculate the average of the grades entered. Maybe the program is to be used for classes of varying sizes. It may be possible to solve the problem by using a sentinelcontrolled loop instead of a count-controlled loop. A sentinel is a special value, outside the range of expected inputs, which is used to signal that there is no more data to be entered. A sentinel-controlled loop continues to iterate as long as the sentinel value has not been read.

41

*** See the program LoopWSentinel.java on webct


This program is a modification of our program to calculate and display the average of the grades entered by the user. The program will work for any number of grades. The grade 999 is used as a sentinel value. The user is asked to enter this value after the last grade is entered to signal the end of input. We read the first grade before the loop so that grade has a value for the initial evaluation of the continuation expression. This type of read is called a priming read. This read is outside the loop so it will not be repeated. Notice there is another read at the bottom of the loop to get the next value of grade before the subsequent evaluation of the continuation expression. In our program, the grade 999 is used as a sentinel value. The variable total is an accumulator. We also have a counter variable named gradeCount that is used to count the number of grades in the total.
42

ANOTHER USER-CONTROLLED LOOP

*** See the program AvgOfGrades.java on webct

This version of our program to calculate the average of the grades entered by the user works for any number of grades greater than one. Since a do-while loop is used for the repetition, the body of the loop is executed once before the continuation expression is evaluated. This is ok as long as it is reasonable to expect that there is at least one grade.

43

INPUT VALIDATION LOOPS


According to the text, input validation is the process of inspecting data given to a program by the user and determining if it is valid. A good program should give clear instructions about the kind of input that is acceptable, and not assume the user has followed these instructions. An input validation loop should: 1. Display a descriptive error message. 2. Prompt the user for a valid input. 3. Read the users input. An input validation loop continues to iterate until the user enters valid input.

44

*** See the program AvgOfGradesWInputValid.java on webct

45

NESTED LOOPS

There are no restrictions on what statements can be inside the body of a loop. Therefore, it is possible to have a loop inside a loop. We call this nesting of loops. In the program AvgOfGradesWInputValid.java, we have two while loops inside the body of a do-while loop.

46

NESTED LOOPS

We can use nested loops to repeatedly perform a repetitive operation.

47

Problem: Suppose we wanted to calculate and display the annual income for each of a companys three divisions and the annual income for the company as a whole from the monthly incomes of each division which are entered by the user.

48

Pseudocode for IncomeByDivision.java Assign the value 0 to the companys annual income For each division from 1 to 3 Assign the value 0 to the annual income for the division For each month from 1 to 12 Get the current divisions monthly income for the current month While the monthly income is negative Display an error message Get the current divisions monthly income for the current month Add the monthly income to the annual income for the division Display the annual income for the current division Add the current divisions annual income to the companys annual income Display the annual income for the company

49

*** See the program IncomeByDivision.java on webct

When I am working on a program, I include debug statements to help me ensure that my program is working as I planned. In a program like this one, I would display the value of the counter(s), the value(s) entered by the user, and the value of the accumulator(s) in each iteration of the loop. I take the debug statements out when I have completed the testing of the program.

50

NESTED LOOPS

The inner loop of a nested loop goes through all of its iterations for each iteration of the surrounding loop.

Note: The statements in the inner for loop of IncomeByDivision.java, that are outside the while loop execute 3 12 = 36 times.

51

THE break STATEMENT

When a break statement is encountered inside a loop, execution immediately goes to the first statement following the loop. When a break statement is encountered multiple levels deep inside a nested loop, only the loop immediately surrounding the break is exited.

52

THE continue STATEMENT

The continue statement causes a loop to stop its current iteration and begin the next iteration. In a while or do-while loop this means that the execution automatically goes to the evaluation of the continuation expression. If the expression is true, the next iteration begins. In a for loop, this means the execution automatically goes to the update portion of the loop header. The update is executed and then the continuation expression is evaluated. If the expression is true, the next iteration begins.

53

THE break AND continue STATEMENTS

Avoid using the break and continue statements in loops. They make it more difficult to follow the logic of the program.

54

WHICH LOOP SHOULD YOU USE?

A repetitive algorithm can be implemented using any of the three loops: while, do-while, or for. The for loop is well-suited to situations where the exact number of iterations is known. The initialization, continuation, and update expressions can be specified inside the parentheses at the top of the loop. The for loop was designed to simplify the writing of countcontrolled loops. The do-while loop is ideal for situations where you always want the loop to iterate at least once. The do-while loop is a good choice for repeatedly displaying a menu. The while loop is ideal for situations where you do not want the loop to iterate if a condition is false from the beginning. Sentinelcontrolled loops and loops to read an unknown number of items from a file can be more elegantly encoded using a while loop.
55

INTRODUCTION TO FILE INPUT AND OUTPUT


The programs we have studied so far have received a small amount of input data from the user, performed a few calculations, and displayed the values of a few data items in a console window or dialog box. Once the console window clears or the dialog box is closed, the output is lost. When the program stops executing or the computer loses power, the data in the variables is lost. In many applications, we need to store data longer term for reference or additional processing. Data can be stored in a file on some secondary storage device and retrieved for later use.

56

INTRODUCTION TO FILE INPUT AND OUTPUT


An output file is a file a program writes data to. An input file is a file a program reads data from.

57

INTRODUCTION TO FILE INPUT AND OUTPUT


There are two general types of files: text and Binary. A text file contains data that has been encoded as text, using some encoding scheme, like Unicode. Even the numbers in a text file are encoded as a series of characters. Text files can be viewed using a text editor like Notepad. A Binary file contains data that has not been converted to text. You cannot view the contents of a Binary file with a text editor. In this class we will be introduced to text files.

58

INTRODUCTION TO FILE INPUT AND OUTPUT


The Java API provides a number of classes that we can use to work with files. To use these classes, you must include the following import statement at the top of your source file, before any class definitions.
import java.io.*;

59

INTRODUCTION TO FILE INPUT AND OUTPUT


To use a file we will create an instance of the File class. For example, the statement below creates an instance of the File class that represents a file named students.txt and assigns the address of the object to the reference variable named theFile.
File theFile = new File(students.txt");

60

INTRODUCTION TO FILE INPUT AND OUTPUT


You can also let the user specify the name of the file.
String fileName; System.out.print("Enter the name of the file: "); fileName = keyboard.nextLine( ); File theFile = new File(fileName);

61

INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
When we want to write data to a file we will create an instance of the PrintWriter class. The second statement creates an object of the PrintWriter class and assigns the address of the object created to the reference variable named outputFile.
File theFile = new File(students.txt"); PrintWriter outputFile = new PrintWriter(theFile);

62

INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
We are passing a reference to a File object to the constructor of the PrintWriter class. The constructor method creates an empty file and establishes a connection between the file and the PrintWriter object. In our example, a file named students.txt will be created in the current working directory, opened to receive data, and linked with the outputFile object.
File theFile = new File(students.txt"); PrintWriter outputFile = new PrintWriter(theFile);
We are passing the reference variable named theFile to the PrintWriter constructor.

63

INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
If the file you open with a PrintWriter object already exists, the file will be erased and an empty file will be created.

64

INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
You can test if a file exists by using the exists( ) method of a File object. The exists( ) method returns the value true if the file exists. The exists( ) method returns the value false if the file does not exist.

65

INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
If you dont want to erase the file if it already exists, test whether the file exists before creating the PrintWriter object.
File theFile = new File(students.txt"); PrintWriter outputFile; if(theFile.exists( )) // If the file already exists { System.out.println("The file students.txt already exists."); } else // The file does not already exist { // Create the file, open it, and link it with outputFile outputFile = new PrintWriter(theFile); }
66

INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
Once you have opened the file by creating an object of the PrintWriter class, you can write data to the file using the print( ) and/or println( ) methods of the object. You already know how to use the print( ) and println( ) methods of the System.out object to display data in a console window. The print( ) and println( ) methods of a PrintWriter object work in much the same way.

67

INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
For example, the statement below writes the name Niklas Hagman followed by a newline character to the file connected to the PrintWriter object referenced by outputFile.
outputFile.println(Niklas Hagman);

68

INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
Data is written to a file as a continuous stream of characters. For example:
outputFile.println("Niklas Hagman"); outputFile.println("Stu Barnes"); outputFile.println("Sergei Zubov");

The data above is written to the file linked with outputFile as:
Niklas Hagman<newline>Stu Barnes<newline>Sergei Zubov<newline>

We are representing the newline character with <newline>. The newline character separates or delimits the individual data items.
69

INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
outputFile.println("Niklas Hagman"); outputFile.println("Stu Barnes"); outputFile.println("Sergei Zubov");

When you open the file in Notepad you will see the following. The text editor interprets the newline character as a command to go to the next line.

70

INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
The print( ) method does not write the newline character after the data item.

71

INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
For example, when the following statements are executed the contents of the file when viewed in Notepad are:
String name = "Jenny"; String phone = "867-5309"; outputFile.print(name + " "); outputFile.print(phone);

72

INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
Adding a throws Clause to the Method Header In Java, many run-time errors are called exceptions. We say that a Java program throws an exception when certain errors occur. For this course we will think of an exception as a signal that the program cannot continue unless the problem is dealt with. For example, if you try to create a PrintWriter object to open a file, but the file cannot be created because there is not enough available disk space, the PrintWriter object throws an exception of the IOException type.
73

INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
Adding a throws Clause to the Method Header When an exception is thrown, the executing method can either deal with the exception or throw it again. If the main( ) method throws an exception, the program terminates and an error message is displayed. In this class, we will simply allow our methods to rethrow any exceptions.

74

INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
Adding a throws Clause to the Method Header To allow a method to rethrow an exception we write a throws clause in the method header. An example of this is shown in the main( ) method header below:
public static void main(String[ ] args) throws IOException

Any method that uses a PrintWriter object, or any method that calls a method that uses a PrintWriter object and does not deal with the problem signaled by the exception must have this throws clause in its header. Otherwise, the program will not compile. 75

INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
Closing a File After you are done using a file you should close it using the close( ) member function of the PrintWriter object.
outputFile.close( );

76

INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
Closing a File
Most operating systems temporarily write output destined for a file to a file buffer in the computers main memory. When the buffer is filled, the contents of the buffer are written to the file. This improves system performance since interaction with secondary storage is slower than main memory. The close( ) method writes any data that is still in the buffer to the file. Until you close the file, your data may not be in the file on a nonvolatile secondary storage device. Once the file is closed, the connection between the file and the PrintWriter object is removed. In order to access the file using the PrintWriter object, the file must be reopened.
77

*** See the program FileOutput.java that is available on webct


Notice that in FileOutput.java we are creating a file named students.txt in a directory/folder named CS1336 on drive H of the computer. If you do not specify any a drive or drive and directory, the file is created in the current working directory. On a computer running the windows operating system, drives and folders are delimited by backslash characters. Remember when a single backslash character appears in a string literal, it marks the beginning of an escape sequence. Two backslash characters represent a single backslash in a string literal. You only need two backslashes if the path is in a string literal. If the program asks the user to enter the filename, the user does not have to type two backslashes. If the drive or directory/folder does not exist Java will not be able to create them. Java will throw an exception. 78

INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
When writing data to a text file: 1. Include the statement import java.io.*; before the class definitions of your source file. 2. Put the throws IOException clause in the method header of any method that uses a PrintWriter object or calls a method that uses a PrintWriter object. 3. Create an object of the File class in memory. Pass the name of the file as the argument to the constructor. 4. Test if the file already exists using the File objects exists( ) member method if you dont want to erase an existing file. 5. Create a PrintWriter object in memory. Pass the reference to the File object created above as the argument to the constructor. The file represented by the File object will be created in memory, linked with the PrintWriter object, and opened for writing. 6. Use the PrintWriter objects member methods println( ) and/or print( ) to write data to the file. 79 7. Use the PrintWriter objects close( ) member method to close the file.

*** See the program SavePlayerStats.java that is available on webct

80

INTRODUCTION TO FILE INPUT AND OUTPUT Reading Data From a File


We will read from a file in a sequential manner. When a file is opened for input, the read position is the first byte of the file. As data is read, the read position advances through the file.

81

INTRODUCTION TO FILE INPUT AND OUTPUT Reading Data From a File


Previously, we read data entered at the keyboard by creating an object of the Scanner class and linking this object to the System.in object which represents the keyboard, and then using the Scanner classes methods nextLine( ), nextDouble( ), nextInt( ), etc. We can also use the Scanner class to read input from a file.

82

INTRODUCTION TO FILE INPUT AND OUTPUT Reading Data From a File


First create an instance of the File class with a statement like the following:
File studentFile = new File("students.txt");

Then create an object of the Scanner class that is linked to the File object by writing a statement like the following:
Scanner inputFile = new Scanner(studentFile);

Notice, that in the statement above, we are passing a reference to a File object to the constructor of the Scanner class. This statement opens an existing file for input and links it with the object referenced by inputFile. In our example, the file named students.txt is opened in the current working directory. 83

INTRODUCTION TO FILE INPUT AND OUTPUT Reading Data From a File


Adding a throws Clause to the Method Header If the File object referenced by the variable you pass to the constructor of the Scanner class represents a file that does not exist, the Scanner object will throw an exception of the IOException type. To rethrow this exception you must have the throws IOException clause in any method that passes a File reference to a Scanner objects constructor or any method that calls a method that passes a File reference to a Scanner objects constructor.

84

INTRODUCTION TO FILE INPUT AND OUTPUT Reading Data From a File


You should test that a file exists before you try to open a file for input. Use a File objects exists( ) method for this before passing the File reference to the Scanner classes constructor. This way you get to control what happens when the file does not exist. At a minimum you can provide a user-friendly error message instead of the one generated by Java in case of an IOException.

85

INTRODUCTION TO FILE INPUT AND OUTPUT Reading Data From a File


For example we could write:
File studentFile = new File("students.txt"); Scanner inputFile; if(studentFile.exists( ) == false) { System.out.println("\nError: the file students.txt does not exist."); System.out.print("The program will now end because it cannot run ); System.out.println(without the input data in the file."); } else // The file exists { inputFile = new Scanner(studentFile); }
86

INTRODUCTION TO FILE INPUT AND OUTPUT Reading Data From a File


Once the file is open, you can read data from the file using the nextLine( ), nextDouble( ), nextInt( ), etc. methods of the Scanner class. For example, the statement below can be used to read all the characters in the file linked with the inputFile object from the current read position to the first newline character.
someString = inputFile.nextLine( );

Remember, the nextLine( ) method reads through the newline character, but does not put the newline character in the string. Reading characters from a file does not remove them from the file, they are still in the file.
87

INTRODUCTION TO FILE INPUT AND OUTPUT Reading Data From a File


Detecting the End of a File Using the Scanner Classes hasNext( )Method Usually, we do not know the exact number of items in a file. Objects of the Scanner class have a method named hasNext( ) which can be used to determine if there is more data in the file. If there is more data in the file, the hasNext( ) method returns the value true. If the end of the file has been reached the hasNext( ) method returns the value false.
88

INTRODUCTION TO FILE INPUT AND OUTPUT Reading Data From a File


Detecting the End of a File Using the Scanner Classes hasNext( )Method We often use the value of the hasNext( ) method in a loop continuation expression to construct a loop that continues to read data from the file until all the data has been read.
while(inputFile.hasNext( ) == true) // You could write while(inputFile.hasNext( )) { /* Put statements here to read data from the file using inputFiles member methods nextLine( ),nextDouble( ), nextInt( ), etc and then process the data as desired. */ }
89

INTRODUCTION TO FILE INPUT AND OUTPUT Reading Data From a File


Closing a File When you are done with the input file, close the file by using the Scanner objects member method close( ).
inputFile.close( );

90

*** See the program FileInput.java which is available on webct

91

INTRODUCTION TO FILE INPUT AND OUTPUT Reading Data From a File


When reading data from a text file:
1. Include the statement import java.io.*; before the class definitions of your source file. 2. Put the throws IOException clause in the method header of any method that passes a File reference to the Scanner classes constructor or calls a method that passes a File reference to a Scanner classes constructor. 3. Create an object of the File class in memory. Pass the name of the file as the argument to the constructor. 4. Use the File objects exists( ) member method to ensure that the file exists. 5. Create a Scanner object in memory. Pass the reference to the File object created above as the argument to the constructor. The file represented by the File object will be opened and linked with the Scanner object if the file exists. 6. Use the Scanner objects member method hasNext( ) to determine if there is more data in the file to be read. 7. Use the Scanner objects member methods nextLine( ), nextDouble( ), nextInt( ), etc. to read data from the file. 8. Use the Scanner objects close( ) member method to close the file.
92

*** See the program GetHighBattAvgs.java which is available on webct

93

You might also like