Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Exceptions and I/O

Similar presentations


Presentation on theme: "Java Exceptions and I/O"— Presentation transcript:

1 Java Exceptions and I/O

2 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

3 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 }

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

5 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

6 Java Streams Input stream Output stream

7 Byte stream classes

8 Character Stream Classes

9 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)?

10 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

11 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?

12 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 ();

13 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 {

14 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: }

15 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.

16 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?

17 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;

18 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) {

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

20 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.

21 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.

22 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.

23 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.

24 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 , UTF-8 or UTF-16. (What are these?)

25 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?

26 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

27 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?

28 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

29 Java Strings Methods of interest: equals equalsIgnoreCase endsWith
SE Winter 2005 8/2/2018 Java Strings Methods of interest: equals equalsIgnoreCase endsWith indexOf lastIndexOf startsWith substring toLowerCase toUpperCase Look over the following URL: Lecture 2

30 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!

31 Acknowledgments The Java I/O slides are derived from Dennis Mumaugh


Download ppt "Java Exceptions and I/O"

Similar presentations


Ads by Google