Lab 9
Lab 9
OBJECT-ORIENTED PROGRAMMING
LAB 9: EXCEPTIONS AND FILE HANDLING
I. Objective
After completing this lab tutorial, you can:
II. Motivation
There are three types of errors:
- Syntax errors occur when the rule of the language is violated and detected by the compiler.
- Run-time errors occur when the computer detects an operation that cannot be carried out (e.g.,
division by zero, x/y is syntactically correct, but if y is zero at run-time a run-time error will
occur).
- Logic errors occur when a program does not perform the intended task.
Instead of deciding how to deal with an error, Java provides the exception mechanism:
- Indicate an error (exception event) has occurred.
- Let the user decide how to handle the problem in a separate section of code specific to that
purpose.
- Crash the program if the error is not handled.
The following Java programs will illustrate the use of Exception Indication.
import java.util.Scanner;
import java.util.InputMismatchException;
do {
System.out.println("Enter an integer number");
try {
int num = sc.nextInt();
System.out.println("num = " + num);
isError = false;
} catch (InputMismatchException e) {
System.err.println("Incorrect input");
sc.nextLine(); // skip newline
isError = true;
}
} while (isError);
}
}
The File class has many useful methods for creating and getting information about files.
Note: To create a file in a specific directory (requires permission), specify the path of the file and use
double backslashes to escape the "\" character (for Windows). You can just write the path on Mac and
Linux, like /Users/name/filename.txt.
2. Write to a File
In the following example, we use the BufferedFileWriter class together with its write() method
to write some text to the file we created in the example above. Note that when you are done writing to
the file, you should close it with the close() method:
import java.io.BufferedWriter; // Import the BufferedWriter class
import java.io.FileWriter; // Import the FileWriter class
import java.io.IOException; // Import the IOException class to handle errors
Note: Many available classes in the Java API can be used to write files in Java: FileWriter,
BufferedWriter, PrintWriter, FileOutputStream, etc.
3. Read a File
In the following example, we use the BufferedFileWriter class to read the contents of the text file
we created in the example above.
import java.io.BufferedReader; // Import the BufferedReader class
import java.io.FileReader; // Import the FileReader class
import java.io.IOException; // Import this class to handle errors
Note: Many available classes in the Java API can be used to read in Java: FileReader,
BufferedReader, Scanner, FileInputStream, etc. Which one to use depends on the Java version
you're working with and whether you need to read bytes or characters, the size of the file/lines, etc.
4. Get File Information
To get more information about a file, use any of the File methods:
5. Delete a File
To delete a file in Java, use the delete() method:
V. Exercises
1. Create class Calculator has 2 methods below:
- public double divide(int a, int b)
- If the values of a and b are outside the range [-1000, 1000], the method throws an
exception NumberOutOfRangeException with the message “Number is outside the
computation”. NumberOutOfRangeException is a student-defined exception.
You can choose any pair of BufferedReader/BufferedWriter or Scanner/PrintWriter to do the
exercises that have read/write file requirements below.
2. Write a Java program:
- Read all contents from an input.txt file.
- Then uppercase all contents and write the results to the output.txt file.
For example:
input.txt output.txt
3. Write a method public static <E> boolean writeFile(String path, ArrayList<E> lst) to write
the generic ArrayList and apply it to write the result of exercise 3 in the Classwork section of
Lab 8 to a file with format sName - sID - gpa with each line is one Student object, instead of
print on the command prompt. (Hint: You can define the toString() method for each class)
4. Write a Java program:
- Get specific files by extensions from a given folder.
- Check if a file or directory specified by pathname exists or not.
- Check if the given pathname is a directory or a file.
- Append text to an existing file.
- Find the longest word in a text file.
5. Write a Java program:
- Read all integers from an input.txt file.
- Then calculate the sum of them and write the result to the output.txt file.
input.txt output.txt
0 12 8 4 140
6 100 1 9