CSE 143 Lecture 21 I/O Streams; Exceptions; Inheritance read 9.3, 6.4 slides created by Marty Stepp

Slides:



Advertisements
Similar presentations
I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1.
Advertisements

1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
Lecture 15: I/O and Parsing
Yoshi
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
Java Exceptions. Exceptions Often in computing, operations cannot properly execute because some sort of error has occurred. Some examples: Often in computing,
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
Copyright 2008 by Pearson Education Building Java Programs Chapter 6 Lecture 6-1: File Input with Scanner reading: , 5.3 self-check: Ch. 6 #1-6.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr.
CSE 143 Lecture 3 Inheritance slides created by Marty Stepp
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 6: File Processing.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
Io package as Java’s basic I/O system continue’d.
Lecture 7 Exceptions and I/O. Overview of the exception hierarchy A simplified diagram of the exception hierarchy in Java Throwable ErrorException IOException.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Exceptions 1. Your computer takes exception Exceptions are errors in the logic of a program (run-time errors). Examples: Exception in thread “main” java.io.FileNotFoundException:
Prepared by : A.Alzubair Hassan Kassala university Dept. Computer Science Lecture 2 I/O Streams 1.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
1 BUILDING JAVA PROGRAMS CHAPTER 6 FILE PROCESSING.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
CSE 143 Lecture 23 Polymorphism; the Object class read slides created by Marty Stepp and Ethan Apter
CSE 143 Lecture 6 Inheritance; binary search reading: 9.1, ; 13.1 slides created by Marty Stepp
Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in.
CMSC 202 Text File I/O. Aug 8, Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-2: Static Data; More Inheritance reading:
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
Building Java Programs Bonus Slides I/O Streams; Exceptions; Inheritance Copyright (c) Pearson All rights reserved.
Java I/O 1. Java I/O (Input and Output) is used to process the input and produce the output based on the input. The java.io package contains all the classes.
1 Text File Input and Output. Objectives You will be able to Write text files from your Java programs. Read text files in your Java programs. 2.
1 CSE 331 Memento Pattern and Serialization slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Introduction to Exceptions in Java CS201, SW Development Methods.
Building Java Programs Chapter 6 File Processing Copyright (c) Pearson All rights reserved.
Lecture 25: Inheritance and Polymorphism
OO Design and Programming II I/O: Reading and Writing
Introduction to programming in java
CSE 143 Lecture 22 I/O Streams; Exceptions; Inheritance read 9.3, 6.4
Streams and File I/O.
Lecture 9-2: Interacting with the Superclass (super);
I/O Basics.
Chapter 17 Binary I/O Dr. Clincy - Lecture.
CSE 143 Lecture 22 The Object class; Polymorphism read
URL in Java C343 Lab (Week 13).
Exceptions and Error-Handling
CSE 143 Lecture 22 The Object class; Polymorphism read
Lecture 25: I/O Streams; Exceptions; Inheritance
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
Law firm employee analogy
CSE 331 Memento Pattern slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
TCSS 143, Autumn 2004 Lecture Notes
Lecture 25: Inheritance and Polymorphism
CSE 143 Lecture 25 I/O Streams; Exceptions; Inheritance read 9.3, 6.4
Building Java Programs
CSE 143 Lecture 23 Polymorphism; the Object class read
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
CSE 143 Lecture 23 Inheritance and the Object class; Polymorphism
Presentation transcript:

CSE 143 Lecture 21 I/O Streams; Exceptions; Inheritance read 9.3, 6.4 slides created by Marty Stepp

2 Input and output streams stream: an abstraction of a source or target of data –8-bit bytes flow to (output) and from (input) streams can represent many data sources: –files on hard disk –another computer on network –web page –input device (keyboard, mouse, etc.) represented by java.io classes –InputStream –OutputStream

3 Streams and inheritance all input streams extend common superclass InputStream ; all output streams extend common superclass OutputStream –guarantees that all sources of data have the same methods –provides minimal ability to read/write one byte at a time

4 Input streams constructing an input stream: (various objects also have methods to get streams to read them) methods common to all input streams: MethodDescription public int read() throws IOException reads/returns a byte (-1 if no bytes remain) public void close() throws IOException stops reading Constructor public FileInputStream(String name) throws IOException public ByteArrayInputStream(byte[] bytes) public SequenceInputStream(InputStream a, InputStream b)

5 Reading from the web –class java.net.URL represents a web page's URL –we can connect to a URL and read data from that web page Method/ConstructorDescription public URL(String address) throws MalformedURLException creates a URL object representing the given address public String getFile(), getHost(), getPath(), getProtocol() public int getPort() returns various parts of the URL as strings/integers public InputStream openStream() throws IOException opens a stream for reading data from the document at this URL

6 Output streams constructing an output stream: methods common to all output streams: MethodDescription public void write(int b) throws IOException writes a byte public void close() throws IOException stops writing (also flushes) public void flush() throws IOException forces any writes in buffers to be written Constructor public FileOutputStream(String name) throws IOException public ByteArrayOutputStream() public PrintStream(File file) public PrintStream(String fileName)

7 int vs. char The read and write methods work an int (byte) at a time. For text files, each byte is just an ASCII text character. –an int can be cast to char as needed: FileInputStream in = new FileInputStream("myfile.txt"); int n = in.read(); // 81 char ch = (char) n; // 'Q' –a char can be passed where an int is wanted without casting: FileOutputStream out = new FileOutputStream("outfile.txt"); char ch = 'Q'; out.write(ch);

8 I/O and exceptions exception: An object representing an error. –checked exception: One that must be handled for the program to compile. Many I/O tasks throw exceptions. –Why? When you perform I/O, you must either: –also throw that exception yourself –catch (handle) the exception

9 Throwing an exception public type name ( params ) throws type { throws clause: Keywords on a method's header that state that it may generate an exception. –Example: public class ReadFile { public static void main(String[] args) throws FileNotFoundException { "I hereby announce that this method might throw an exception, and I accept the consequences if it happens."

10 Catching an exception try { statement(s); } catch ( type name ) { code to handle the exception } –The try code executes; if the given exception occurs, the try block stops running, it jumps to the catch block and runs that try { Scanner input = new Scanner(new File("foo")); System.out.println(input.nextLine()); } catch (FileNotFoundException e) { System.out.println("File was not found."); }

11 Dealing with an exception All exception objects have these methods: Some reasonable ways to handle an exception: –try again; re-prompt user; print a nice error message; quit the program; do nothing (!) MethodDescription public String getMessage() text describing the error public String toString() a stack trace of the line numbers where error occurred public InputStream openStream() throws IOException opens a stream for reading data from the document at this URL getCause, getStackTrace, printStackTrace other methods

12 Exception inheritance All exceptions extend from a common superclass Exception

13 Inheritance and exceptions You can catch a general exception to handle any subclass: try { Scanner input = new Scanner(new File("foo")); System.out.println(input.nextLine()); } catch (Exception e) { System.out.println("File was not found."); } Similarly, you can state that a method throws any exception: public static void foo() throws Exception {... –Are there any disadvantages of doing so?

14 Exceptions and errors There are also Error s, which represent serious Java problems. –Error and Exception have common superclass Throwable. –You can catch an Error (but you probably shouldn't)

15 Exercise Write a class Downloader with the following behavior: –public Downloader(String url) Initializes the downloader to examine the given URL. –public void download(String targetFileName) Downloads the file from the URL to the given file name on disk. Write client program DownloadMain to use Downloader : URL to download? foo bar Bad URL! Try again: Target file name: out.html Contents of out.html : ZOMBO...

16 Exercise solution import java.io.*; import java.net.*; public class Downloader { private URL url; // Constructs downloader to read from the given URL. public Downloader(String urlString) throws MalformedURLException { url = new URL(urlString); } // Reads downloader's URL and writes contents to the given file. public void download(String targetFileName) throws IOException { InputStream in = url.openStream(); FileOutputStream out = new FileOutputStream(targetFileName); while (true) { int n = in.read(); if (n == -1) { // -1 means end-of-file break; } out.write(n); } in.close(); out.close(); }

17 Exercise solution 2 import java.io.*; import java.net.*; import java.util.*; public class DownloadMain { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("URL to download? "); String urlString = console.nextLine(); Downloader down = null; // create a downloader; while (down == null) { // re-prompt the user if this fails try { down = new Downloader(urlString); } catch (MalformedURLException e) { System.out.print("Bad URL! Try again: "); urlString = console.nextLine(); } System.out.print("Target file name: "); String targetFileName = console.nextLine(); try { // download bytes to file (print error if it fails) down.download(targetFileName); } catch (IOException e) { System.out.println("I/O error: " + e.getMessage()); }

18 Inheritance inheritance: Forming new classes based on existing ones. –a way to share/reuse code between two or more classes –superclass: Parent class being extended. –subclass: Child class that inherits behavior from superclass. gets a copy of every field and method from superclass –is-a relationship: Each object of the subclass also "is a(n)" object of the superclass and can be treated as one.

19 Inheritance syntax public class name extends superclass { public class Lawyer extends Employee {... } override: To replace a superclass's method by writing a new version of that method in a subclass. public class Lawyer extends Employee { // overrides getSalary method in Employee class; // give Lawyers a $5K raise public double getSalary() { return ; }

20 super keyword Subclasses can call inherited methods/constructors with super super. method ( parameters ) super( parameters ); public class Lawyer extends Employee { public Lawyer(int years) { super(years); // calls Employee constructor } // give Lawyers a $5K raise public double getSalary() { double baseSalary = super.getSalary(); return baseSalary ; } –Lawyers now always make $5K more than Employees.

21 Exercise 2 Write class TallyDownloader to add behavior to Downloader : –public TallyDownloader(String url) –public void download(String targetFileName) Downloads the file, and also prints the file to the console, and prints the number of occurrences of each kind of character in the file. URL to download? ZOMBO... { =21, =42, !=1, "=18, #=4, %=4,,=3, -=14,.=10, /=18, 0=15, 1=9, 2=2, 3=1, 4=5, 5=5, 6=4, 7=1, 8=3, 9=2, :=3, ;=1, =17, ?=1, A=1, B=3, C=2, D=3, E=2, F=19, M=1, O=2, P=3, S=1, T=2, V=2, Z=2, _=2, a=42, b=13, c=27, d=18, e=47, f=7, g=10, h=28, i=32, j=2, k=5, l=24, m=21, n=17, o=36, p=12, q=3, r=17, s=24, t=37, u=8, v=10, w=15, x=5, y=6, z=2}

22 Exercise solution public class TallyDownloader extends Downloader { public TallyDownloader(String url) throws MalformedURLException { super(url); // call Downloader constructor } // Reads from URL and prints file contents and tally of each char. public void download(String targetFileName) throws IOException { super.download(targetFileName); Map counts = new TreeMap (); FileInputStream in = new FileInputStream(targetFileName); while (true) { int n = in.read(); if (n == -1) { break; } char ch = (char) n; if (counts.containsKey(ch)) { counts.put(ch, counts.get(ch) + 1); } else { counts.put(ch, 1); } System.out.print(ch); } in.close(); System.out.println(counts); // print map of char -> int }

23 Exercise solution 2 import java.io.*; import java.net.*; import java.util.*; public class DownloadMain { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("URL to download? "); String urlString = console.nextLine(); Downloader down = null; // create a tallying downloader; while (down == null) { // re-prompt the user if this fails try { down = new TallyDownloader(urlString); } catch (MalformedURLException e) { System.out.print("Bad URL! Try again: "); urlString = console.nextLine(); }... }