Copyright(c) Systems and Computer Engineering, Carleton Univeristy, 2001 1 94.204* Object-Oriented Software Development Unit 13 I/O Stream Hierarchy Case.

Slides:



Advertisements
Similar presentations
A Guide to Advanced Java Faculty:Nguyen Ngoc Tu. 2 Operating System Application #1 Application #2 Java Virtual Machine #1 Local Memory Shared Memory Threads.
Advertisements

1 Streams and Input/Output Files Part I. 2 Introduction So far we have used variables and arrays for storing data inside the programs. This approach poses.
Chapter 19 Binary I/O.
Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
Lecture 15: I/O and Parsing
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.
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.
Java I/O and Java Networking (Client Side) Yoshi.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L07 (Chapter 18) Binary I/O.
Algorithm Programming I/O via Java Streams Bar-Ilan University תשס"ח by Moshe Fresko.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 18 Binary I/O.
Advanced Java Class Serialization. Serialization – what and why? What? –Translating the contents of an Object to a series of bytes that represent it,
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L08 (Chapter 18) Binary I/O.
Lab 2 Data Streams. Lab 2: Data Streams Introduction Reading from an Input Stream Writing to an Output Stream Filter Streams.
Java I/O Input: information brought to program from an external source
CS203 Programming with Data Structures Input and Output California State University, Los Angeles.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 19 Binary I/O.
CSC – Java Programming II Lecture 9 January 30, 2002.
Chapter 15: Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams F Use JFileChooser F Text Input.
Files and Streams. Java I/O File I/O I/O streams provide data input/output solutions to the programs. A stream can represent many different kinds of sources.
Prepared by : A.Alzubair Hassan Kassala university Dept. Computer Science Lecture 2 I/O Streams 1.
Chapter 17 Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams  Use JFileChooser F Text Input.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Java How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
JAVA I/O © EnhanceEdu, IIIT Hyderabad. Contents 3/29/2010EnhanceEdu, IIIT - H 2  Command Line I/O  File Class  Streams  Byte Streams [Low level and.
Object Persistence and Object serialization CSNB534 Asma Shakil.
Java Programming: Advanced Topics 1 Input/Output and Serialization Chapter 3.
Applications Development Input and Output in Java Topics covered: Some input-output capabilities of Java Example input code Java.
Java Input/Output CSE301 University of Sunderland Harry Erwin, PhD Half Lecture.
Input/output Input in java is stream based.A stream represents sequence of bytes or characters. Stream provides an abstract view of I/O. Stream can be.
L5: Input & Output COMP206, Geoff Holmes and Bernhard Pfahringer.
Two Ways to Store Data in a File  Text format  Binary format.
Java Input/Output. Reading standard input Surprisingly complicated (GUI focus) Old-fashioned way: BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
CIS 270—App Dev II Big Java Chapter 19 Files and Streams.
1 Software 1 Java I/O. 2 The java.io package The java.io package provides: Classes for reading input Classes for writing output Classes for manipulating.
Streams & Files. Java I/O Classes Saving data to / Loading data from files Two Choices: Binary-Formatted or Text-Formatted Data – int x = 1234; – Binary.
– Advanced Programming P ROGRAMMING IN Lecture 22 Input and Output System.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 19 Binary I/O.
1 Chapter 19 Binary I/O. 2 Motivations F Data stored in a text file – is represented in human-readable form –Text file –Readable –Java source programs.
Company Input/Output Stream –. Input/Output Stream Data Program Input Stream Output Stream.
Exception Handling, Reading and Writing in Files, Serialization, Exceptions, Files, Streams, File Readers and Writers, Serializable SoftUni Team Technical.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 13 Java Fundamentals File I/O Serializing an.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Files in Java 1.
1 Putting Streams to use. 2 Stream Zoo C++ gives you istream, ostream, iostream, ifstream, ofstream, fstream, wistream, wifstream, istrsteam… (18) Java.
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.
Java Programming: Advanced Topics 1 Input/Output and Serialization.
Java Programming, Second Edition Chapter Sixteen File Input and Output.
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
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
Java IO Exploring the java.io package and living to talk about it.
Chapter 10: I/O Streams Input Streams Output Streams
The Java IO System Different kinds of IO Different kinds of operations
Chapter 17 Input and Output
Exception Handling, Reading and Writing in Files, Serialization,
Ch14 Files and Streams OBJECTIVES
Chapter 8: Input and Output
Chapter 17 Binary I/O.
Object Writing in files
I/O Basics.
Chapter 17 Binary I/O 1.
Java Programming Course
Chapter 17 Binary I/O Dr. Clincy - Lecture.
CSE 331 Memento Pattern slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Files and Streams in Java
CS 240 – Advanced Programming Concepts
David Davenport Spring 2005
Presentation transcript:

Copyright(c) Systems and Computer Engineering, Carleton Univeristy, * Object-Oriented Software Development Unit 13 I/O Stream Hierarchy Case Study of an Inheritance Hierarchy revised January 30, 2001

Copyright(c) Systems and Computer Engineering, Carleton Univeristy, I/O Streams All input and output in Java is based on streams. A stream is a flow of data with a reader on one end and a writer on the other end –Streams are sequences of bytes –Streams in Java are one-way. –A Writer = Anything that can send a sequence of bytes –A Reader = Anything that can receive a sequence of bytes Preview ! Seamless interchange between terminals, files, URLs, blocks of memory, sockets (remote computers) Writer Reader

Copyright(c) Systems and Computer Engineering, Carleton Univeristy, In the package java.io, there is an inheritance hierarchy of streams supported InputStream and OutputStream are abstract classes –Concrete subclasses must be provided; Instantitate these. Stream are objects to/from which data are sent/received. Because all I/O objects are subclassed from InputStream & OutputStream, they can be used interchangeably (type-casting along class hierarchy) Java I/O Stream Classes InputStream OutputStream ConcreteInputSubclasses ConcreteOutputSubclasses

Copyright(c) Systems and Computer Engineering, Carleton Univeristy, Java.io.InputStream Full UML of java.io.InputStream java.io.InputStream read():int read(:byte[]):int read(:byte[],:off:int,len:int):int skip(n:long):long available():int close():int reset() mark(readLimit:int) markSupported():boolean read() is the only abstract method (UML : Italics for abstract) read() is the lowest-level interface for all streams : a flow of byte-level data. Other read methods are implemented in terms of this one Other methods provide default behaviour, to be overridden by subclasses.

Copyright(c) Systems and Computer Engineering, Carleton Univeristy, Java.io.OutputStream Full UML of java.io.OutputStream java.io.OutputStream write():int write(:byte[]):int write(:byte[],:off:int,len:int):int flush() write() is the only abstract method Other write methods are implemented in terms of this one.

Copyright(c) Systems and Computer Engineering, Carleton Univeristy, Java I/O Class Design The Problem : –Although everything is ultimately a series of bytes, we don’t want to manipulate bytes; We want to program at a higher level (abstraction!) –There is a great variety of scenarios to cover Data abstraction : Instead of bytes, let’s read int, float, char Higher-level : As well as the primitive types, we want to support I/O of classes, such as String but also user-defined classes Sources : Terminal, File, URL, ….sockets Behaviours : Buffering, look-ahead, random-access

Copyright(c) Systems and Computer Engineering, Carleton Univeristy, Java I/O Class Design The Java approach is a pluggable solution –A Layered approach based on stream wrapper or filters : Java supplies you with a whole slew of filters (as classes), where each class adds one type of behaviour. You can then layer (or wrap) these filters in any pattern to achieve the kind of behaviour you require. In the next slides, we look at the major parts of the full I/O hierarchy, but in stages. The breakdown is artificial and serves only to break discussion into manageable pieces. We also look first at the Input side, then follow with the Output File Buffered Data

Copyright(c) Systems and Computer Engineering, Carleton Univeristy, Java Input Class Hierarchy Part I : At the first level of the Input hierarchy are a set of concrete subclasses that can be viewed as the “source” Allows you to connect a stream to a particular type of source. InputStream FileInputStream PipedInputStream StringBufferInputStream ObjectInputStream ByteArrayInputStream Reading from sockets (remote communication) Reading from files Reading from string buffers Reading from byte array(memory) Reading from any object

Copyright(c) Systems and Computer Engineering, Carleton Univeristy, Java Input Class Hierarchy Example : Using one of the “source” InputStream subclasses. Suppose we wish to read from a file : FileInputStream istream = new FileInputStream("t.tmp"); istream.read(); // FileInputStream must provide implementation istream.read(bytes,n); // Could have used InputStream’s version, // FileInputStream overrides for efficiency You can only read bytes or arrays of bytes from this file.

Copyright(c) Systems and Computer Engineering, Carleton Univeristy, Java Input Class Hierarchy Part II : There is a second level of the I/O hierarchy which is collectively called the filter or stream wrappers –Filters add behaviour to the stream InputStream FileInputStream PipedInputStream StringBufferInputStream ObjectInputStream ByteArrayInputStream FilterInputStream It is another abstract class. In order to learn how to use it, We must look at its concrete Subclasses.

Copyright(c) Systems and Computer Engineering, Carleton Univeristy, Java Input Class Hierarchy Part II : FilterInputStream InputStream PushbackInputStream BufferedInputStream DataInputStream CheckedInputStream LineNumberInputStream FilterInputStream DigestInputStream InflaterInputStream GZIPInputStreamZipInputStream JarInputStream

Copyright(c) Systems and Computer Engineering, Carleton Univeristy, Summary of Input Filter Classes BufferedInputStream : Adds the ability to buffer, and support for mark() and reset() methods. PushBackInputStream : Adds the ability to “unread” something. DataInputStream : Support for primitive data types LineNumberInputStream : Keeps track of the current line number where a line is a sequence of bytes followed by a CR CheckedInputStream :Adds the ability to maintain a checksum on the data (for data integrity) DigestInputStream : A security mechanism for reading messages “digested” in a transparent stream of bits. InflaterInputStream : Allows the reading of compressed data.

Copyright(c) Systems and Computer Engineering, Carleton Univeristy, Java Input Class Hierarchy Example : Using one of the “filter” InputStream subclasses. Continuing from the previous example, suppose we wish to read data from a file : FileInputStream istream = new FileInputStream("t.tmp"); DataInputStream dstream = new DataInputStream(istream); int i = dstream.readInt(); char c = dstream.readChar(); String line = dstream.readLine(); Wrapping the FileInputStream Into a DataInputStream ! Now can read integers, Characters, whole lines, Instead of just bytes.

Copyright(c) Systems and Computer Engineering, Carleton Univeristy, Stream Wrapping How does Stream Wrapping Work ? Take a look at any of the constructors for the filter classes. eg. public DataInputStream(InputStream in) The constructor is part of a chain : Input : The parameter to the constructor is an inputstream. But you don’t have to use an InputStream; you can use any subclass of InputStream. Output : The object created by the constructor is a DataInputStream (which is itself a subclass of InputStream and thus could be used for further wrapping in another filter class). Because all the input subclasses inherit from java.io.InputStream, they can be used as the input in the constructor of another stream.

Copyright(c) Systems and Computer Engineering, Carleton Univeristy, Java Output Class Hierarchy The Output Class Hierarchy follows as similar format OutputStream FileOutputStream PipedOutputStream ObjectOutputStream ByteArrayOutputStream Writing to sockets (remote communication) Writing to files Writing to byte array(memory) Writing to any object FilterOutputStream

Copyright(c) Systems and Computer Engineering, Carleton Univeristy, Java Output Class Hierarchy Part II : FilterOutputStream OutputStream BufferedOutputStream DataInputStream CheckedOutputStream DigestOutputStream FilterInputStream PrintStream DeflaterOutputStream GZIPOutputStreamZipOutputStream JarOutputStream

Copyright(c) Systems and Computer Engineering, Carleton Univeristy, I/O Examples : Writing Objects to a file FileOutputStream ostream = new FileOutputStream("t.tmp"); ObjectOutputStream p = new ObjectOutputStream(ostream); int i = 5; p.writeInt(i); p.writeObject( “Writing a String object” ); p.writeUTF(“Writing a string as primitive data”); p.writeObject( new Date (2001,1,21)); ostream.close();

Copyright(c) Systems and Computer Engineering, Carleton Univeristy, Detour About Object Streams : Serializable When you write an object to an OutputStream (eg. To a file), what information must be stored in order for it to be read back from an InputStream ? –Object Type –Data that describes the current state of the object Reading and writing objects involves a process called serialization. –Applied only to objects, not to primitive data types (which use DataInput/Output interfaces) –Saves objects in a particular file format (Details are not important in order to use, but interested people are referred to Core Java) –Java provides default serialization. In order to use this, your class must simply identify itself by implementing java.io.Serializable

Copyright(c) Systems and Computer Engineering, Carleton Univeristy, Detour About Object Streams : Serializable package java.io; /** … The serialization interface has no methods or fields and serves only to identify the semantics of being serializable. To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. **/ public interface Serializable { static final long serialVersionUID = L; } Like Cloneable, this is a “tagging” interface (no methods) JVM supplies a default serialization process to any objects tagged as Serializable; You don’t have to provide any implementation yourself if the default is fine.

Copyright(c) Systems and Computer Engineering, Carleton Univeristy, Detour About Object Streams : Serializable You can also override the serializing methods, and provide your own private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException; private void writeObject(ObjectOutputStream out) throws IOException; These will override the default, reading & writing the object’s data- but not its superclass’s. In order to provide a completely new serialization mechanism, you must implement java.io.Externalizable Why ? Security : Java’s serialization format is well-known and can be hacked. But that’s a whole other course !

Copyright(c) Systems and Computer Engineering, Carleton Univeristy, Java I/O Class Hierarchy : Interfaces Suppose we now want to read/write from/to a Random Access file –Behaviour : Access any specified location in a file Solution ? Weakness : –Random access is not a stream because it is not a sequence of bytes; –Moreover, a random access file permits both read and write! –You can’t subclass it from Input/OutputStream yet they do indeed share many behaviours (eg. Reading/writing primitive data types), suggesting that a better solution is by way of interfaces. InputStream OutputStream RandomAccess

Copyright(c) Systems and Computer Engineering, Carleton Univeristy, Java I/O Class Hierarchy : Interfaces Quoting from Jbuilder : The DataInput interface provides for reading bytes from a binary stream and reconstructing from them data in any of the Java primitive types. InputStream FilterInputStream DataInputStream DataInput OutputStream FilterOutputStream DataOutputStream DataOutput RandomAccessFile Shares behaviour With IOStream Has Own Behaviour Too : Both Input & Output!

Copyright(c) Systems and Computer Engineering, Carleton Univeristy, Java I/O Class Hierarchy A second look at the ObjectInput/OutputStreams –When reading/writing objects, you are ultimately reading/writing primitive data types –You often want to read both primitive types and objects from a stream. Conclusion : Reading/writing objects shares and extends behaviour of reading/writing data ObjectInputStream ObjectInput DataInput Quoting from Jbuilder : ObjectInput extends the DataInput interface to include the reading of objects. DataInput includes methods for the input of primitive types, ObjectInput extends that interface to include objects, arrays, and Strings. Similarly for Output

Copyright(c) Systems and Computer Engineering, Carleton Univeristy, Reader/Writer Class Hierarchy. InputStream and OutputStream operate on sequences of bytes. –Used for reading/writing binary data. –eg. Files are binary files  Cannot view them for text editors. There is a whole separate hierarchy, mostly duplicated, that operates on UNICODE text eg. Files are text files  Can view with a text editor. InputStreamOutputStream ReaderWriter