Streams www.espirity.com Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com) Portions of the notes for this lecture include excerpts from.

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

I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1.
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.
1 Streams and Input/Output Files Part 3. 2 Handling Primitive Data Types The basic input and output streams provide read/write methods that can be used.
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.
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.
The Package Statement Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts –private package classes not visible.
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.
III. Streams. Introduction Often a program needs to bring in information from an external source or to send out information to an external destination.
COMP201 Java Programming Topic 5: Input and Output Reading: Chapter 12.
Standard input, output and error. Lecture Under Construction.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L07 (Chapter 18) Binary I/O.
File I/O in Java CS 311, Winter File Basics Recall that a file is block structured. What does this mean? What happens when an application opens.
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.
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 ->
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
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.
5-Oct-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Streams and Files Maj Joel Young.
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 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.
Java Programming: Advanced Topics 1 Input/Output and Serialization Chapter 3.
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.
Two Ways to Store Data in a File  Text format  Binary format.
© Amir Kirsh Files and Streams in Java Written by Amir Kirsh.
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.
1 CISC 370: I/O Streams James Atlas June 24, 2008.
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.
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.
DEPARTMENT OF COMPUTER SCIENCE N.HARIKA. Contents Overview of I/O Streams Character Streams Byte Streams Using the Streams 2.
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.
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.
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
java.io supports console and file I/O
The Java IO System Different kinds of IO Different kinds of operations
Lecture 8: I/O Streams types of I/O streams Chaining Streams
CSG2H3 Object Oriented Programming
IO in java.
Chapter 17 Input and Output
Exception Handling, Reading and Writing in Files, Serialization,
OO Design and Programming II I/O: Reading and Writing
Chapter 17 Binary I/O.
Object Writing in files
I/O Basics.
Chapter 17 Binary I/O 1.
File I/O & collection frame work
Java Programming Course
JAVA IO.
Files and Streams in Java
Web Design & Development Lecture 8
Java Basics Introduction to Streams.
Streams and Readers The stream hierarchy is for reading bytes, the reader/writer hierarchy is for reading characters Unicode characters can be used internationally,
David Davenport Spring 2005
Presentation transcript:

Streams www.espirity.com Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com) Portions of the notes for this lecture include excerpts from the Eclipse 3.0 Help facility. These excerpts are made available under CPL for ease of use by instructors, (c) Copyright (c) 2000, 2004 IBM Corporation and others. For more complete information instructors are encouraged to read the full notes from the Eclipse Help facility.

Additional Contributors None as of September, 2004

Module Overview Streams In this section we discuss Streams in Java.

Module Road Map Streams What are streams? Stream types Character streams Byte streams Filter streams Object Serialization The module road map slide gives a view on what sections are in the module and what are the topics covered in the current section.

What is a Stream? From an abstract point of view a stream is simply a sequence From an implementation point of view you can think of a stream as a list A stream has a start, and end, and a position Streams can let us model systems that have state without ever using assignment or mutable data It is possible to model bank account using streams and without using assignment operation or mutable data. All bank transactions can be in the stream and account balance could be calculated by moving through the stream of transactions, instead of modeling it as a field in BankAccount class.

Stream Concept To read data serially, a Java program: Opens a stream to a data source file remote socket Reads the information serially To write data serially, a Java program: Writes the information serially Data source type doesn’t matter, concepts of reading and writing are the same Once you understand the top level classes (java.io.Reader, java.io.Writer), the remaining classes are much of the same

Stream Types Two different types of streams: Character streams Support reading and writing of characters, text Contain 16-bit Unicode characters Supported through Reader and Writer classes Byte streams Support reading and writing of any bytes Contain 8-but bytes Supported through InputStream and OutputStream classes It is possible to do conversion between character streams and byte stream InputStreamReader and OutputStreamWriter classes can be used

Character Streams vs. Byte Streams Character streams (reader and writer) should be used because: They can handle any character in the Unicode character set (while the byte streams are limited to ISO-Latin-1 8-bit bytes) They are easier to internationalize because they are not dependent upon a specific character encoding They use buffering techniques internally and are therefore potentially much more efficient than byte streams Byte streams should be used for handling binary data, such as image and sound files All stream classes are in the java.io package

Character Streams Hierarchy Object InputStream Reader OutputStream Writer <<abstract>> Reader <<abstract>> Writer FileReader BufferedReader FileWriter BufferedWriter

Reader and Writer classes Parent classes for character-stream based classes Used to read and write 16-bit character streams Important methods for reading and writing to streams found in these and their descendent classes include the following: int read() int read(char buffer[]) int read(char buffer[], int offset, int length) int write(int aCharacter) int write(char buffer[]) int write(char buffer[], int offset, int length)

FileReader and FileWriter classes FileReader is used for reading streams of characters from a file FileWriter is used for writing streams of characters to a file File inputFile = new File("source.txt"); File outputFile = new File("final.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int aCharacter; while ((aCharacter = in.read()) != 1) out.write(aCharacter); in.close(); out.close(); FileReader class inherits from InputStremaReader class that inherits from Reader class. FileWriter class inherits from OutoutStremaReader class that inherits from Writer class. It’s important to close the stream

Writing and Reading Example Create a file Read the file FileWriter writefile = new FileWriter("source.txt"); writefile.write('A'); writefile.write("bcdefghi"); writefile.close(); myString Abcdefghi FileReader inFile = new FileReader("source.txt"); inFile.skip(3); // skips next 3 chars ('A' 'b' 'c' ) char[] characterArray = new char[10]; inFile.read(characterArray ); // ['d' 'e' 'f' 'g' 'h' 'i'] String myString = new inFile.read(characterArray).trim(); inFile.close();

BufferedReader and BufferedWriter classes Used for buffering characters as being read or written Buffer is used for storing data without conversion Buffer size can be set Should wrap any reader/writer whose read/write operations may be inefficient BufferedReader reader = new BufferedReader(new DataInputStream(System.in)); String input; while ((input = reader.readLine()) != null) { ... //do something interesting here } Using BufferedReader and BufferedWriter classes may be very efficient in improving overall performance of reading data from streams and writing data to streams. Without them each read or write operation on data results in data being read/written and converted into characters/bytes right away, which may be time consuming. With buffered reader/writer, read and write operations only read/write data without converting them. The conversion is done when streams close, or when buffer is full.

Byte Streams Hierarchy InputStream FileInputStream FilterInputStream ObjectInputStream DataInputStream BufferdInputStream Filter streams Filter streams Object streams OuputStream In the next few slides we will look at the byte streams hierarchy and most commonly used byte stream classes. FileOutputStream FilterOutputStream ObjectOutputStream DataOutputStream BufferdOutputStream PrintStream

Specialized Byte Streams File streams Used for writing data to files and reading data from files Object streams Used for reading and writing objects Also called object serialization Filter streams Used for filtering data as it’s being read from streams, or written to the streams They work with primitive data types (int, double, boolean) They implement DataInput and DataOutput interfaces

Filter Streams Filter data as it's being read from or written to a stream Subclasses of the FilterInputStream a and FilterOutputStream Constructed on another stream (the underlying stream) Read method reads input from the underlying stream, filters it, and passes on the filtered data to the caller Write method writes data to the underlying stream Filtering done by the streams depends on the stream Some streams buffer the data, some count data as it goes by, and others convert data to another form

Using Filter Streams… For reading primitive data types DataInputStream class can be used FileInputStream inputFile = new FileInputStream("price.cat"); DataInputStream inputStream = new DataInputStream(inputFile); double price= inputStream.readDouble(); inputStream.close(); It’s important to know what’s in the stream

…Using Filter Streams For writing primitive data types A DataOutputStream can be used FileOutputStream outputFile = new FileInputStream("price.cat"); DataOutputStream outputStream = new DataInputStream(outputFile ); outputStream.writeDouble(234.56); outputStream.flush(); outputStream.close(); Forces data to be written flush() method forces data to be written. If not used, data are written either when stream is closed or when buffer is full.

Streams in System Class System.in - standard input An instance of BufferedInputStream class Used to read lines of text that user enters System.out - standard output Instance of PrintStream class Used to send text to the Console System.err - error output Used to send error text to the error file BufferedReader reader = new BufferedReader(new DataInputStream(System.in)); String input; while ((input = reader.readLine()) != null){ System.out.println(input);}

Object Serialization Supported with ObjectOutputStream class Serialized object class must implement the Serializable interface GregorianCalendar calendar = new GregorianCalendar(); ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream("calendar.dat")); out.writeObject(calendar); out.close(); Above example shows GregorianCalendar being serialized into a file. It is possible to serialize an instance of this class as its super class (Calendar) implements Serializable interface. public class java.util.GregorianCalendar extents java.util.Calendar{… public class java.util. GregorianCalendar extents java.lang.Object implements java.lang.Cloneable, java.io.Serializable{…

Serialization Protocol Classes that perform serialization and deserialization must implement special methods: Object state is saved by writing the individual fields to the ObjectOutputStream Object state is retrieved by reading the individual fields back from the ObjectInputStream private void writeObject(java.io.ObjectOutputStream out) throws IOException private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException; writeObject method is responsible for writing the state of the object to the stream readObject method is responsible for reading the state of the object from the stream

Object Deserialization Supported with ObjectInputStream class You must know the order in which things were written in order to cast to the correct type ObjectInputStream in = new ObjectInputStream (new FileInputStream("calendar.dat")); GregorianCalendar calendar = (GregorianCalendar)in.readObject(); in.close(); It’s important to know what’s in the stream for casting

Module Summary In this module you have learned: What streams are What are different types of streams in Java Differences between character streams and byte streams What filter streams are Streams used in the System class How to serialize objects

Labs Slide! Let’s do the labs. Lab: Steams