Download presentation
Presentation is loading. Please wait.
Published byMelinda Haynes Modified over 9 years ago
1
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 13: Streams and Exceptions 1 Chapter 13 Streams and Exceptions
2
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 2 Chapter 13: Streams and Exceptions 2 Streams, Readers and Writers Stream: read/write bytes Reader/Writer: read/write characters FileReader reader = new FileReader("input.txt"); FileInputStream in = new FileInputStream(fname); Same for FileWriter, FileOutputStream
3
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 3 Chapter 13: Streams and Exceptions 3 Reading Characters and Bytes Reader reader =...; int next = reader.read(); char c; if (next!=-1) c = (char)next; InputStream in =...; int next = in.read(); byte b; if (next!=-1) b = (byte)next; Use write to write a char / byte
4
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 4 Chapter 13: Streams and Exceptions 4 Figure 1 A German Keyboard
5
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 5 Chapter 13: Streams and Exceptions 5 Figure 2 The Thai Script
6
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 6 Chapter 13: Streams and Exceptions 6 Figure 3 The Chinese Script
7
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 7 Chapter 13: Streams and Exceptions 7 Reading and Writing Text If you want to read/write more than a character, must use wrappers: PrintWriter out = new PrintWriter(writer); Now can use println xBufferedReader in = new BufferedReader(reader); Now can use readLine
8
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 8 Chapter 13: Streams and Exceptions 8 Closing Files Close file by calling the close method reader.close(); writer.close(); Ok to call close on wrapper; it'll close the underlying file
9
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 9 Chapter 13: Streams and Exceptions 9 Exceptions Without exceptions: Program for failure if (!x.doStuff()) return false; With exceptions: Don't worry about failure in normal code x.doStuff(); y.doMore();
10
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 10 Chapter 13: Streams and Exceptions 10 Throwing an Exception When an unforeseen situation happens, just throw a suitable exception object: if (input == null) { EOFException ex = new EOFException("..."); throw ex; } Or simply throw new EOFException("...");
11
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 11 Chapter 13: Streams and Exceptions 11 Exception Control Flow When an exception is thrown, the method containing the throw statement doesn't return to its caller Instead, the closest matching catch clause is located If there is no matching catch clause, then the program terminates
12
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 12 Chapter 13: Streams and Exceptions 12 Catching Exceptions try {......... } catch (IOException e) {... } catch (NumberFormatException e) {... }
13
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 13 Chapter 13: Streams and Exceptions 13 Catching Exceptions Put as many statements in the try block as possible Not necessary to catch all exceptions If you don't know how to handle an exception, don't catch it
14
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 14 Chapter 13: Streams and Exceptions 14 Ensuring Resource Cleanup BufferedReader in = null; try { in = new BufferedReader(new FileReader("in.txt")); } finally { if (in != null) in.close(); }
15
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 15 Chapter 13: Streams and Exceptions 15 Checked Exceptions Checked exceptions—cause is external –Unexpected EOF –File not found even though it should be there Unchecked exceptions—cause is programmer's incompetence –Call through null reference –Array index out of bounds Method must declare all checked exceptions
16
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 16 Chapter 13: Streams and Exceptions 16 Declaring Exceptions public void readProducts (BufferedReader in) throws IOException {... } Rule of Thumb: It is better to throw than to catch. Catch only in a few places (e.g. main) Any function calling this function must also catch or declare
17
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 17 Chapter 13: Streams and Exceptions 17 Exception Hierarchy All exception classes extending Error or RuntimeException are unchecked All exceptions extending Exception but not RuntimeException are checked
18
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 18 Chapter 13: Streams and Exceptions 18 Figure 4 A Part of the Exception Class Hierarchy
19
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 19 Chapter 13: Streams and Exceptions 19 Figure 5 Plotting Product Performance against Price
20
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 20 Chapter 13: Streams and Exceptions 20 Figure 6 A File Chooser Dialog
21
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 21 Chapter 13: Streams and Exceptions 21 Program PlotProducts.java import java.awt.Container; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowAdapter; import java.awt.geom.Ellipse2D; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem;
22
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 22 Chapter 13: Streams and Exceptions 22 import javax.swing.JPanel; import javax.swing.JOptionPane; import javax.swing.JTextField; public class PlotProducts { public static void main(String[] args) { PlotProductsFrame frame = new PlotProductsFrame(); frame.setTitle("Product Plot"); frame.show(); } class PlotProductsFrame extends JFrame { public PlotProductsFrame() { final int DEFAULT_FRAME_WIDTH = 300; final int DEFAULT_FRAME_HEIGHT = 300; setSize(DEFAULT_FRAME_WIDTH,DEFAULT_FRAME_HEIGHT);
23
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 23 Chapter 13: Streams and Exceptions 23 addWindowListener(new WindowCloser()); // add panel to content pane Container contentPane = getContentPane(); panel = new ProductPanel(); contentPane.add(panel, "Center"); // set menu items JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); MenuListener listener = new MenuListener();
24
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 24 Chapter 13: Streams and Exceptions 24 openMenuItem = new JMenuItem("Open"); fileMenu.add(openMenuItem); openMenuItem.addActionListener(listener); exitMenuItem = new JMenuItem("Exit"); fileMenu.add(exitMenuItem); exitMenuItem.addActionListener(listener); } /** Handles the open file menu. Prompts user for file name and reads products from file. */ public void openFile() { BufferedReader in = null; try { // show file chooser dialog JFileChooser chooser = new JFileChooser(); if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
25
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 25 Chapter 13: Streams and Exceptions 25 { // construct reader and read products File selectedFile = chooser.getSelectedFile(); in = new BufferedReader (new FileReader(selectedFile)); plotProducts(in); } catch(FileNotFoundException e) { JOptionPane.showMessageDialog (null, "Bad filename. Try again."); } catch(IOException e) { JOptionPane.showMessageDialog (null, "Corrupted file. Try again."); }
26
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 26 Chapter 13: Streams and Exceptions 26 finally { if (in != null) try { in.close(); } catch(IOException e) { JOptionPane.showMessageDialog (null,"Error closing file."); } /** Reads products and adds them to the product panel. @param in the buffered reader to read from */ public void plotProducts(BufferedReader in) throws IOException { panel.clearProducts(); boolean done = false;
27
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 27 Chapter 13: Streams and Exceptions 27 while (!done) { Product p = new Product(); if (p.read(in)) panel.addProduct(p); else // last product read done = true; } private JMenuItem openMenuItem; private JMenuItem exitMenuItem; private ProductPanel panel;
28
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 28 Chapter 13: Streams and Exceptions 28 private class MenuListener implements ActionListener { public void actionPerformed(ActionEvent event) { Object source = event.getSource(); if (source == openMenuItem) openFile(); else if (source == exitMenuItem) System.exit(0); } private class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent event) { System.exit(0); }
29
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 29 Chapter 13: Streams and Exceptions 29 class ProductPanel extends JPanel { public ProductPanel() { final int PRODUCTS_LENGTH = 100; products = new Product[PRODUCTS_LENGTH]; productsSize = 0; } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; // compute price range if (productsSize == 0) return; // nothing to plot double minPrice = products[0].getPrice(); double maxPrice = products[0].getPrice();
30
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 30 Chapter 13: Streams and Exceptions 30 for (int i = 1; i < productsSize; i++) { double price = products[i].getPrice(); if (price < minPrice) minPrice = price; if (price > maxPrice) maxPrice = price; } final int MAX_SCORE = 100; UnitConverter units = new UnitConverter(minPrice,maxPrice, 0, MAX_SCORE, getWidth(), getHeight()); // draw a labeled point for each product for (int i = 0; i < productsSize; i++) { Product p = products[i]; double x = units.xToPixel(p.getPrice()); double y = units.yToPixel(p.getScore());
31
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 31 Chapter 13: Streams and Exceptions 31 final double SMALL_CIRCLE_RADIUS = 2; Ellipse2D.Double circle = new Ellipse2D.Double( x - SMALL_CIRCLE_RADIUS, y - SMALL_CIRCLE_RADIUS, 2 * SMALL_CIRCLE_RADIUS, 2 * SMALL_CIRCLE_RADIUS); g2.draw(circle); g2.drawString(p.getName(), (float)x, (float)y); } /** Clears all products from the graph and repaints it. */ public void clearProducts() { productsSize = 0; repaint(); }
32
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 32 Chapter 13: Streams and Exceptions 32 /** Adds a new product to the graph and repaints it. @param p the product to add */ public void addProduct(Product p) { if (productsSize < products.length) { products[productsSize] = p; productsSize++; } repaint(); } private Product[] products; private int productsSize; }
33
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 33 Chapter 13: Streams and Exceptions 33 Command Line Arguments java Prog -v input.dat Command line arguments in args parameter of main args[0]: "-v" args[1]: "input.dat" Caesar cipher program java Crypt input.txt encrypt.txt java Crypt -d encrypt.txt output.txt
34
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 34 Chapter 13: Streams and Exceptions 34 Figure 7 The Caesar Cipher
35
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 35 Chapter 13: Streams and Exceptions 35 Program Crypt.java import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Crypt { public static void main(String[] args) { boolean decrypt = false; int key = DEFAULT_KEY; FileReader infile = null; FileWriter outfile = null; if (args.length 4) usage(); // gather command line arguments and open files
36
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 36 Chapter 13: Streams and Exceptions 36 try { for(int i = 0; i < args.length; i++) { if (args[i].substring(0, 1).equals("-")) // it is a command line option { String option = args[i].substring(1, 2); if (option.equals("d")) decrypt = true; else if (option.equals("k")) { key = Integer.parseInt (args[i].substring(2)); if (key = NLETTERS) usage(); } else { if (infile == null) infile = new FileReader(args[i]); else if (outfile == null) outfile = new FileWriter(args[i]);
37
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 37 Chapter 13: Streams and Exceptions 37 } catch(IOException e) { System.out.println("Error opening file"); System.exit(0); } if (infile == null || outfile == null) usage(); // encrypt or decrypt the input if (decrypt) key = NLETTERS - key; try { encryptFile(infile, outfile, key); infile.close(); outfile.close(); }
38
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 38 Chapter 13: Streams and Exceptions 38 catch(IOException e) { System.out.println("Error processing file"); System.exit(0); } /** Prints a message describing proper usage and exits. */ public static void usage() { System.out.println ("Usage: java Crypt [-d] [-kn] infile outfile"); System.exit(1); }
39
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 39 Chapter 13: Streams and Exceptions 39 /** Encrypts a character with the Caesar cipher. Only upper- and lowercase letters are encrypted. @param c the character to encrypt @param k the encryption key @return the encrypted character */ public static char encrypt(char c, int k) { if ('a’ <= c && c <= 'z') return (char)('a’ + (c - 'a’ + k) % NLETTERS); if ('A’ <= c && c <= 'Z') return (char)('A’ + (c - 'A’ + k) % NLETTERS); return c; }
40
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 40 Chapter 13: Streams and Exceptions 40 /** Encrypts all characters in a file. @param in the plaintext file @param out the file to store the encrypted characters @param k the encryption key */ public static void encryptFile(FileReader in, FileWriter out, int k) throws IOException { while (true) { int next = in.read(); if (next == -1)return; // end of file char c = (char)next; out.write(encrypt(c, k)); } public static final int DEFAULT_KEY = 3; public static final int NLETTERS = 'z’ - 'a’ + 1; }
41
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 41 Chapter 13: Streams and Exceptions 41 Figure 8 Public Key Encryption
42
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 42 Chapter 13: Streams and Exceptions 42 Figure 9 Sequential and Random Access
43
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 43 Chapter 13: Streams and Exceptions 43 Figure 10 The File Pointer
44
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 44 Chapter 13: Streams and Exceptions 44 Figure 11 Variable-Size and Fixed-Size Records
45
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 45 Chapter 13: Streams and Exceptions 45 Program Database.java import java.io.IOException; import java.io.RandomAccessFile; public class Database { public static void main(String[] args) { ConsoleReader console = new ConsoleReader(System.in); System.out.println ("Please enter the data file name:"); String filename = console.readLine(); try { RandomAccessFile file = new RandomAccessFile(filename, "rw"); long nrecord = file.length() / RECORD_SIZE; boolean done = false; while (!done) { System.out.println ("Please enter the record to update (1 - " + nrecord + "), new record (0), quit (-1)"); int pos = console.readInt();
46
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 46 Chapter 13: Streams and Exceptions 46 if (1 <= pos && pos <= nrecord) // update record { file.seek((pos - 1) * RECORD_SIZE); Product p = readProduct(file); System.out.println("Found ” + p.getName() + ” ” + p.getPrice() + ” ” + p.getScore()); System.out.println ("Enter the new price:"); double newPrice = console.readDouble(); p.setPrice(newPrice); file.seek((pos - 1) * RECORD_SIZE); writeProduct(file, p); } else if (pos == 0) // add record { System.out.println("Enter new product:"); String name = console.readLine(); System.out.println("Enter price:"); double price = console.readDouble(); System.out.println("Enter score:");
47
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 47 Chapter 13: Streams and Exceptions 47 int score = console.readInt(); Product p = new Product(name, price, score); file.seek(nrecord * RECORD_SIZE); writeProduct(file, p); nrecord++; } else if (pos == -1) done = true; } file.close(); } catch(IOException e) { System.out.println("Input/Output Exception ” + e); }
48
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 48 Chapter 13: Streams and Exceptions 48 /** Reads a fixed-width string. @param f the file to read from @param size the number of characters to read @return the string with leading and trailing spaces removed */ public static String readFixedString(RandomAccessFile f, int size) throws IOException { String b = “"; for (int i = 0; i < size; i++) b += f.readChar(); return b.trim(); } /** Writes a fixed-width string. @param f the file to write to @param size the number of characters to write */
49
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 49 Chapter 13: Streams and Exceptions 49 public static void writeFixedString(RandomAccessFile f, String s, int size) throws IOException { if (s.length() <= size) { f.writeChars(s); for (int i = s.length(); i < size; i++) f.writeChar(’ '); } else f.writeChars(s.substring(0, size)); } /** Reads a product record. @param f the file to read from @return the next product stored in the file. */
50
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 50 Chapter 13: Streams and Exceptions 50 public static Product readProduct(RandomAccessFile f) throws IOException { String name = readFixedString(f, NAME_SIZE); double price = f.readDouble(); int score = f.readInt(); return new Product(name, price, score); } /** Writes a product record. @param f the file to write to */
51
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 51 Chapter 13: Streams and Exceptions 51 public static void writeProduct(RandomAccessFile f, Product p) throws IOException { writeFixedString(f, p.getName(), NAME_SIZE); f.writeDouble(p.getPrice()); f.writeInt(p.getScore()); } public static final int NAME_SIZE = 30; public static final int CHAR_SIZE = 2; public static final int INT_SIZE = 4; public static final int DOUBLE_SIZE = 8; public static final int RECORD_SIZE = CHAR_SIZE * NAME_SIZE + DOUBLE_SIZE + INT_SIZE; }
52
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 52 Chapter 13: Streams and Exceptions 52 Figure 12 Relational Database Files
53
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 53 Chapter 13: Streams and Exceptions 53 Figure 13 A Social Security Card
54
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 54 Chapter 13: Streams and Exceptions 54 Object Streams Saves an entire object: Product p =...; ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("...")); out.writeObject(p); Read in from ObjectInputStream : p = (Product)in.readObject();
55
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 55 Chapter 13: Streams and Exceptions 55 Object Streams Even better: Put all objects in a Vector and save the vector! All saved classes must implement Serializable interface No methods—just tag class Product implements Serializable {... }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.