Java Exceptions and I/O

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.
Jan Java I/O Yangjun Chen Dept. Business Computing University of Winnipeg.
Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
Lecture 15: I/O and Parsing
Exceptions. Definition Exception: something unexpected that can occur in the execution of a program e.g., divide by zero or attempt to open a file that.
MOD III. Input / Output Streams Byte streams Programs use byte streams to perform input and output of 8-bit bytes. This Stream handles the 8-bit.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
COMP201 Java Programming Topic 5: Input and Output Reading: Chapter 12.
10-1 Writing to a Text File When a text file is opened in this way, a FileNotFoundException can be thrown – In this context it actually means that the.
Geoff Holmes Overview IO Zoo Stream I/O File I/O Buffering Random-Access Text Streams Examples Serialization Java IO – programs that start with import.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
Chapter 8: Exceptions and I/O Streams Copyright 2002, Matthew Evett. These slides are based on slides copyrighted by John Lewis and William Loftus, 2002,
Files and Streams CS 21a. 10/02/05 L18: Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Java I/O – what does it include? Command line user interface –Initial arguments to main program –System.in and System.out GUI Hardware –Disk drives ->
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
Java Programming: I/O1 Java I/O Reference: java.sun.com/docs/books/tutorial/essential/io/
Streams and File I/O Chapter 14. I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or.
Very Brief Introduction to Java I/O with Buffered Reader and Buffered Writer.
Prepared by : A.Alzubair Hassan Kassala university Dept. Computer Science Lecture 2 I/O Streams 1.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
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.
Based on OOP with Java, by David J. Barnes Input-Output1 The java.io Package 4 Text files Reader and Writer classes 4 Byte stream files InputStream, FileInputStream,
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
File IO Basics By Dan Fleck Coming up: Data Streams.
By Rachel Thompson and Michael Deck.  Java.io- a package for input and output  File I/O  Reads data into and out of the console  Writes and reads.
May 27, 2015JDP Networking Part II Networking Part II May 27, of 72.
Files and Streams CS /02/05 L7: Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
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.
– Advanced Programming P ROGRAMMING IN Lecture 22 Input and Output System.
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.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
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.
1 Putting Streams to use. 2 Stream Zoo C++ gives you istream, ostream, iostream, ifstream, ofstream, fstream, wistream, wifstream, istrsteam… (18) Java.
Simple Java I/O Part I General Principles. Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
Java Input / Output l a modular approach to input/output: - different stream objects are connected/wrapped to handle I/O l a data stream object: a flow.
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit9: Internet programming 1.
The Java IO System Different kinds of IO Different kinds of operations
Keerthi Nelaturu Url: site.uottawa.ca/~knela006
Lecture 8: I/O Streams types of I/O streams Chaining Streams
Java Text I/O CS140 Dick Steflik. Reader Abstract super class for character based input Subclasses: – BufferedReader – CharArrayReader – FilterReader.
IO in java.
OO Design and Programming II I/O: Reading and Writing
Lesson 8: More File I/O February 5, 2008
Streams and File I/O.
Java Developer Program May 17, 2017
I/O Streams A stream is a sequence of bytes that flows from a source to a destination In a program, we read information from an input stream and write.
I/O Basics.
Creating and Modifying Text part 2
I/O Streams- Basics Byte Streams and Character Streams
CSS161: Fundamentals of Computing
Streams and File I/O Chapter 14.
CHAPTER 5 (PART 2) JAVA FILE INPUT/OUTPUT
I/O Streams A stream is a sequence of bytes that flow from a source to a destination In a program, we read information from an input stream and write information.
Workshop for Programming And Systems Management Teachers
Input and Output Stream
Workshop for Programming And Systems Management Teachers
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
I/O and Applet from Chapter 12
Files and Streams in Java
Web Design & Development Lecture 8
CS 240 – Advanced Programming Concepts
Streams and Readers The stream hierarchy is for reading bytes, the reader/writer hierarchy is for reading characters Unicode characters can be used internationally,
Exceptions 10-May-19.
David Davenport Spring 2005
Presentation transcript:

Java Exceptions and I/O

Java Exception Handling An exception is an occurrence, usually an error, that disrupts the normal execution flow of a program, e.g. opening a file which doesn’t exist writing past the end of an array dividing by zero running out of memory Java provides an elegant way of separating the code that deals with exceptions from “normal” code

Java Exception Handling All exceptions are subclasses of java.lang.Throwable Handled using the try … catch … finally statement, e.g. URL url; try { url = new URL("xyz"); ... } catch (MalformedURLException ex) { // url is undefined } catch (IOException ex) { // any other IO exceptions } finally { // this executed no matter what }

Declaring your own exceptions public class AuthException extends IOException { public AuthException () {} public AuthException (String msg) {super(msg);} }

Java I/O Much of network programming is about simple I/O – moving bytes from one system to another I/O in Java is based on streams Input streams read data; output streams write data Different stream classes are used for different sources of data – but all have the same basic methods Filter streams can be chained to input or output streams for modifying data or to provide additional functionality Readers and Writers handle text streams rather than byte streams

Java Streams Input stream Output stream

Byte stream classes

Character Stream Classes

I/O in Java Java has four basic classes for I/O: OutputStream: sends binary data InputStream: receives binary data Writer: sends text data Reader: receives text data Everything else (sockets, files, System.out etc. are subclasses of these). Why two of everything (binary vs. text)?

Files There are two types of files: The standard input, output and error: System.in, System.out and System.err Regular files Files are supported by the File class Most the time you can use a convenience class such as FileReader instead

OutputStream The methods of an output stream are: void write (int b) throws IOException void write (byte[] data) throws IOException void write (byte[] data, int offset, int length) throws IOException void flush () throws IOException void close () throws IOException What do these methods do?

void printHelloWorld (final OutputStream out) { What does this code try to do? What is wrong with it? How can we fix it? void printHelloWorld (final OutputStream out) { final String hw = "Hello, World\n"; for (int i=0; i < hw.length (); i++) { out.write (hw.charAt (i)); } out.close ();

OutputStream 19: void printHelloWorld (final OutputStream out) { 20: try { 21: final String hw = "Hello, World\n"; 22: for (int i=0; i < hw.length (); i++) { 23: out.write (hw.charAt (i)); 24: } 25: out.flush (); 26: } catch (final IOException ex) { 27: // Some error handling code goes here 28: System.err.println ("Oops 1: " + ex); 29: } finally {

OutputStream 29: } finally { 30: // Always a good idea to close streams 31: try { 32: out.close (); 33: } catch (final IOException ex) { 34: // Some more error handling code goes here 35: System.err.println ("Oops 2: " + ex); 36: } 37: } 38: }

OutputStream Where do output streams come from? System.out and System.err. FileOutputStream Socket.getOutputStream() Where do these streams write to? Most other output streams are built on top of these basic ones.

The important methods of an input stream are: int read () throws IOException int read (byte[] input) throws IOException int read (byte[] input, int offset, int length) throws IOException int available () throws IOException void close () throws IOException What do these methods do? What happens at the end of file? Why does read() return an int rather than a byte?

byte[] get128 (final InputStream in) { What does this code try to do? What is wrong with it? How can we fix it? byte[] get128 (final InputStream in) { final byte[] result = new byte[128]; for (int bytesRead = 0; bytesRead < 128;) { final int read = in.read (result, bytesRead, 128-bytesRead); bytesRead = bytesRead + read; } return result;

InputStream 19: byte[] get128 (final InputStream in) { 20: final byte[] result = new byte[128]; 21: try { 22: for (int bytesRead = 0; bytesRead < 128;) { 23: final int read = in.read (result, bytesRead, 128-bytesRead); 24: // Check to see if we hit the end of the stream 25: if (read > 0) { 26: bytesRead = bytesRead + read; 27: } else { 28: // End of stream! 29: break; 30: } 31: } 32: } catch (IOException ex) {

InputStream 32: } catch (IOException ex) { 33: System.err.println ("Oops: " + ex); 34: } finally { 35: return result; 36: } 37: }

InputStream Where do input streams come from? System.in FileInputStream and Socket.getInputStream() Where do these streams read from? Most other input streams are built on top of these basic ones.

Stream Hints Remember to flush output buffers. Remember IOExceptions! (Expect the majority of your code to be exception handling.). Remember that exception handlers can raise exceptions! Use finally to make sure clean-up is always executed. Use close to close any streams you open. Remember to flush output streams before closing them.

Filter streams Raw InputStreams and OutputStreams aren't much use! Often we want to add functionality to an existing stream. For example: A BufferedInputStream which adds buffering to an input stream. A CipherInputStream which decrypts an encrypted input stream. A GZIPInputStream which uncompresses a compressed input stream. Streams which read from other streams are called filter streams in Java.

Filter streams Filter streams can be chained together: final FileInputStream rawIn = new FileInputStream ("foo .des.gz"); final InputStream processedIn = new GZIPInputStream ( new CipherInputStream ( new BufferedInputStream ( rawIn), desCipher)); This is an example of dataflow programming.

Readers and writers Input and OutputStreams handle raw data. Readers and Writers handle text. Most protocols (e.g. HTTP) and data exchange formats (e.g. XML) these days are text based. (Why? Isn't it much more efficient to send binary data?) For example: final OutputStream out = ...; // Create a new text writer with encoding UTF-8 final Writer writer = new OuputStreamWriter (out, "UTF-8"); Common values for the encoding: ISO-8859-1, UTF-8 or UTF-16. (What are these?)

Readers and writers Two very useful methods: String BufferedReader.readLine () PrintWriter.println (String msg) for example from a Socket s: PrintWriter writer = new PrintWriter (new OutputStreamWriter (s.getOutputStream (), "UTF-8")); writer.println ("GET /index.html HTTP/1.1"); writer.flush (); and: BufferedReader reader = new BufferedReader (new InputStreamReader (s.getInputStream (), "UTF-8")); String request = reader.readLine (); Connect these up and what happens?

Readers and writers writer.println ("A message"); Unfortunately, there are several problems with Sun's code:  PrintWriter doesn't throw any IOExceptions, you have to do your error-handling the old-fashioned C way (blech).  Mixing text and binary is very hard! [Note well!!]  BufferedReader and PrintWriter may not agree about what a new line is! For example, on a Mac sending on a socket: writer.println ("A message"); and on any Java machine receiving on a socket: final String line = reader.readLine (); this will deadlock! Why? Harold provides fixes: SafeBufferedReader and SafePrintWriter

Buffered Readers and writers What is buffering? How does it work? BufferedReaders have buffering. Is this a problem? Why? BufferedWriters have buffering. Is this a problem? Why?

BufferedReader input = new BufferedReader(new FileInput(“file.txt”); Tokenizers Now that you have input, what do you do with it? BufferedReader input = new BufferedReader(new FileInput(“file.txt”); Line = input.readLine(); Tokenize it using either StreamTokenizer StringTokenizer Use startsWith and endsWith to examine string Use index to locate elements of interest

Java Strings Methods of interest: equals equalsIgnoreCase endsWith SE 550 - Winter 2005 8/2/2018 Java Strings Methods of interest: equals equalsIgnoreCase endsWith indexOf lastIndexOf startsWith substring toLowerCase toUpperCase Look over the following URL: http://www.javacoffeebreak.com/books/extracts/javanutshell3rdedition/#ch04_02.html Lecture 2

Streams summary Streams programming is the backbone of distributed programming. Java's I/O library supports sophisticated dataflow programming techniques in a modular, scaleable fashion. Using buffered I/O and switching in “mid-stream” is bad Readers and Writers have problems. There are some bugs with Java I/O!

Acknowledgments The Java I/O slides are derived from Dennis Mumaugh http://condor.depaul.edu/~dmumaugh/se550/