Professional Documents
Culture Documents
try {
// code that might throw exception
}
catch ([Type of Exception] e) {
// what to do if exception is thrown
}
Catching Multiple Exceptions
Output:
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 2 at
ExceptionExample.main(ExceptionExample.java:4)
Exception Message
• Example
– java.lang.ArrayIndexOutOfBoundsException: 2 at
ExceptionExample.main(ExceptionExample.java:4)
– What exception class?
– Which array index is out of bounds?
– What method throws the exception?
– What file contains the method?
– What line of the file throws the exception?
Unchecked Exceptions
Files
– Long-term storage of large amounts of data
– Persistent data exists after termination of program
– Files stored on secondary storage devices
• Magnetic disks
• Optical disks
• Magnetic tapes
– Sequential and random access files
Files and Streams
import java.util.Scanner;
import java.io.*;
int sum = 0;
for( ; fileInput.hasNextInt(); ){
sum = sum + fileInput.nextInt();
}
fileOutput.println("The sum is: " + sum);
fileInput.close();
fileOutput.close();
}
}
Reading and Writing Files – Alternative code
catch (IOException exception) {
import java.util.Scanner; System.out.println("File not found");
import java.io.*; }
catch (NumberFormatException exception) {
public class ExampleFile1{ System.out.println("Input was not a
public static void main(String[] args) { number");
}
int sum = 0;
finally{
Scanner fileInput=null; fileOutput.println("The sum is: " + sum);
PrintStream fileOutput=null; fileInput.close();
fileOutput.close();
try { }
fileInput = new Scanner(new File("input.txt")); }
}
fileOutput = new PrintStream (new
File("output.txt"));
// this version is better because it catches
for( ; fileInput.hasNextLine(); ){ // wrong data in the input file
String s = fileInput.nextLine();
sum = sum + Integer.parseInt(s);
}
}
Buffering
• Buffering
– Improves performance of I/O
– Copies each output to a region of memory called a buffer
– Entire buffer output to disk at once
• One long disk access takes less time than many smaller ones
– A program can convert an unbuffered stream into a buffered
stream
• Example
In this example one processes the information stored in the text file
“Inventory.dat”. Each line of this file contains: the name of the
product, the number of items and the price per item, separated by a
space.
Widget 14 3.35
Spoke 132 0.32
Wrap 58 1.92
Thing 28 4.17
Brace 25 1.75
Clip 409 0.12
Cog 142 2.08
Creating an array of objects with data from a text file
import java.util.*;
import java.io.*;
import java.text.*;
try{
// the external file contains each line of data like in the example: chairs 4 45.50
line = inFile.readLine();
infile.close()
for (int scan = 0; scan < count; scan++)
System.out.println (items[scan]);
Continue..
class InventoryItem {
private String name;
private int units; // number of available units of this item
private float price; // price per unit of this item
private DecimalFormat fmt;
public InventoryFrame() {
setSize(300,200);
show();
try {
FileReader fr = new FileReader (file);
inFile = new BufferedReader (fr);
}
catch (IOException ex){
System.out.println ("File missing.");
}
Container c = getContentPane();
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(4,2));
p1.add(new JLabel("Product name"));
Class Inventory as a Frame with Action (II)
t1 = new JTextField(10);
p1.add(t1);
p1.add(new JLabel("Number of units"));
t2 = new JTextField(10);
p1.add(t2);
p1.add(new JLabel("Price per unit"));
t3 = new JTextField(10);
p1.add(t3);
get=new JButton("Get Record from Text File");
p1.add(get);
get.addActionListener(this);
c.add(p1,BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e) {
try { line = inFile.readLine(); }
catch (IOException ex){}
if (line != null){
tokenizer = new StringTokenizer (line);
t1.setText(tokenizer.nextToken());
t2.setText(tokenizer.nextToken());
t3.setText(tokenizer.nextToken());
}
} // end actionPerformed()
import java.io.*;