Streams Reading: 2 nd Ed: 16.1-16.3, 16.5 3rd Ed: 11.1, 19.1, 19.4

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 I. 2 Introduction So far we have used variables and arrays for storing data inside the programs. This approach poses.
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.
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
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.
III. Streams. Introduction Often a program needs to bring in information from an external source or to send out information to an external destination.
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.
Lecture 31 File I/O -Part 2 COMP1681 / SE15 Introduction to Programming.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File 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,
Chapter 91 Streams and File I/O Chapter 9. 2 Reminders Project 6 released: due Nov 10:30 pm Project 4 regrades due by midnight tonight Discussion.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L08 (Chapter 18) Binary I/O.
Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.
Chapter 20 – Streams and Binary Input/Output Big Java Early Objects by Cay Horstmann Copyright © 2014 by John Wiley & Sons. All rights reserved.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
Java I/O Input: information brought to program from an external source
Java File I/O (Continued). File I/O in Java Like every other programming language, Java supports the writing to and reading from different files with.
CS203 Programming with Data Structures Input and Output California State University, Los Angeles.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
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.
CIS 270—Application Development II Chapter 14—Files and Streams.
5-Oct-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Streams and Files Maj Joel Young.
Input / Output Chapter 13.  We use files all the time  Programs are files  Documents are files  We want them to be “permanent”  To last beyond execution.
Prepared by : A.Alzubair Hassan Kassala university Dept. Computer Science Lecture 2 I/O Streams 1.
Java How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
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,
OOP with Java, David J. Barnes Input-Output1 A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated.
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.
12-CRS-0106 REVISED 8 FEB 2013 Java Collection. 12-CRS-0106 REVISED 8 FEB 2013 Java Collection.
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.
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.
 Pearson Education, Inc. All rights reserved Files and Streams.
Outline  Basic IO  File class  The Stream Zoo  Serialization  Regular Expressions.
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.
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.
I/O Basics Java does provide strong, flexible support for I/O related to files and networks. Java’s console based interaction is limited since in real.
Java Input and Output. Java Input  Input is any information needed by your program to complete its execution  So far we have been using InputBox for.
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.
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
1 Input-Output A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated as transparently as.
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
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
CSG2H3 Object Oriented Programming
Ch14 Files and Streams OBJECTIVES
Object Writing in files
12: The Java I/O System stream model.
I/O Basics.
Java Programming Course
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
David Davenport Spring 2005
Presentation transcript:

Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1,

Streams 2 Learning Objectives describe stream abstraction used in Java for byte and character input/output write programs that use streams to read and write data incorporate data persistence in a program using Java's serialization mechanism

Streams 3 Data Storage and Transport Data is stored on disks and in main memory 1. Want to move data from disk to main memory 2. Want to move data from memory on one machine to memory on another machine, across the network Transport mechanisms have limited capacity  Usually measured in bytes per second A stream is like a conveyor belt or pipeline, that allows data to be processed continuously  We don’t want to wait until all the data has arrived, before starting to process API is related to Iterator, although there are differences

Streams 4 Data Storage and Transport Byte Stream Buffer Index Buffered Bytes

Streams 5 Using a Stream A process uses a stream to communicate with  Another process on the same machine, or another machine  A device, e.g. Printer  A file on the disk drive To communicate  Identifies the address of the resource o File name, URL, IP address, etc...  Creates a primitive stream for that address  Wraps the primitive stream with any number of stream filters to create a stream pipeline o Filters also called transformers, wrappers, and decorators  Transfer data through the pipeline  Close the pipeline

Streams 6 Java Stream Types Java provides many stream classes (in the java.io package) to support I/O from devices with different characteristics  These stream classes are all used in basically the same way (it does not matter if the streams goes to a file, another computer, or somewhere else).  Two primitive categories: 1.Byte streams, which are a sequence of (8-bit) bytes used to read/write binary data (images, sound), manipulate raw files, and for object serialization 2.Character streams, which are used to communicate UTF characters in a platform independent way Supports symbols and foreign languages

Streams 7 Stream Classes Byte Input Streams  InputStream o Basic Stream interface  FileInputStream : input comes from a file. o e.g. InputStream stream = new FileInputStream("filename.txt")  URL Inputstream o e.g.: InputStream stream = new URL(“...”).getInputStream() Byte Output Streams  Similar classes with suffix OutputStream

Streams 8 InputStream interface interface InputStream { int read(); //Read next byte in stream // 0 <= returnValue < 256 //Return -1 at end void close(); //Release the stream //Other advanced functionality }

Streams 9 Character Stream Classes Similar kinds of classes as Byte Streams Character Input Streams:  Classes with the suffix Reader Character Output Stream:  Classes with the suffix Writer

Streams 10 Examples 1. Read file into main memory

Streams 11 InputStream without Buffer DISK Java Process disk read 42 FileInputStream read() 42

Streams 12 InputStream with Buffer DISK Java Process disk read 42, 54, 24, ….. read() 42 FileInputStream read() 42, 54, 24, ….. 42, 54, 24, ….Buffer

Streams 13 Example 1. Read file into main memory with buffer 2. Copy file with buffers

Streams 14 Data Conversion Sometimes we want to read/write data types more complex than a simple byte We can attach a DataInputStream / DataOutputStream to any other stream which will filter data and convert it class DataInputStream { byte readByte() char readChar() double readDouble() String readUTF() … } DataInputStream input = new DataInputStream(FileInputStream(“array.bin"));

Streams 15 Stream Processing Pipelines Place objects between streams to perform transformations For example, 1.Read data from file 2.Buffer it 3.Convert it DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(“array.bin"))); Image credit

Streams 16 Byte Streams FileOutputStream FileInputStream A diagram of the classes for handling byte streams

Streams 17 URL class for Web Services We can read data from Web services using the URL class Example Geonames Web service String service = “ URL url = new URL(service); InputStream input = url.openStream(); Service Arguments

Streams 18 Standard Streams java.lang.System’s in, out and err are streams associated with the standard input and output devices  System.in is a static variable of type InputStream  System.out and System.err are static variables of type PrintStream To read character-based data from System.in we need to wrap System.in using an InputStreamReader (and usually a BufferedReader as well to be able to read a line at a time)  E.g., BufferedReader bufferedIn = new BufferedReader( new InputStreamReader(System.in)); String line = bufferedIn.readLine();

Streams 19 Why streams? Streams abstract I/O and support processing of the data in the stream, allowing us to write methods that are more general For example, suppose we want to determine the maximum integer, among a group of values:  in a file  read from the keyboard using System.in  in a String or character array (e.g., "123\n453\n848\n" ) Note that a BufferedReader can be attached to any kind of Reader including: FileReader, InputStreamReader, CharArrayReader, StringReader

Streams 20 Why streams? /** * Read in a set of integers (one per line) and return the maximum value in != null The maximum value read or smallest int value if nothing read IOException on any input exception */ public static int maxInput(BufferedReader in) throws IOException { String line = null; int max = Integer.MIN_VALUE; // smallest int value while ((line = in.readLine()) != null) { int n = Integer.parseInt(line); max = Math.max(max, n); } } return max; }

Streams 21 Why streams? For instance, we can call maxInput where the stream reads data from a text file named mydata BufferedReader bufferedIn = new BufferedReader( new FileReader("mydata")); int max = maxInput(bufferedIn); Or we can call maxInput, reading the data from the standard input System.in BufferedReader bufferedIn = new BufferedReader( new InputStreamReader(System.in)); int max = maxInput(bufferedIn);

Streams 22 Object Serialization Suppose you are writing a program that allows the user to store the names, telephone numbers and addresses of their contacts. When the user enters data, they expect it will be available to them the next time they run the program. To do this, the program needs to store the data (likely on a hard disk) from one session to the next. You can do this easily using object serialization.

Streams 23 Serialization: Object Streams Java’s serialization API supports the saving of the state of an object to a sequence of bytes; those bytes can later be used to restore the object The ability to save an object is sometimes called “persistent objects” Serialization makes it possible to save an object, stop the program, restart it, and then restore the object To make objects of a class serializable, you just need to implement the Serializable interface. Serializable is a marker interface (that means it has no methods)  E.g., to make the Account class serializable: class Account implements Serializable { … }

Streams 24 Saving an Object To save serializable objects in a file we need to  associate a FileOutputStream with the file  wrap an ObjectOutputStream around it  use writeObject() to store the objects sequentially  e.g., if Account implements Serializable and a1, a2 are accounts we can save them in the file named account.dat ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream("account.dat")); out.writeObject(a1); out.writeObject(a2); Most Java library classes are serializable (but not all)  Java takes care of serializing the variables in the class, etc.

Streams 25 Reading Objects from a File To read back in the objects we have saved in a file we need to  associate a FileInputStream with that file  wrap an ObjectInputStream around it  use readObject() to get the objects sequentially, in the order they were saved  e.g., to get the first two accounts stored in account.dat ObjectInputStream in = new ObjectInputStream( new FileInputStream("account.dat")); Account a1 = (Account) in.readObject(); Account a2 = (Account) in.readObject();

Streams 26 Reading Objects from a File If you change the definition of the class in between saving an object and reading it back.... a java.io.InvalidClassException may be thrown It could be days or weeks or years before you read it back serialVersionUID field is used to keep track of which version of a class, an object on disk, corresponds to You should increase the serialVersionUID everytime you add or remove a field of a Serializable class private static final long serialVersionUID

Streams 27 Exercises Chapter 16, Page 603 Questions P16.1, P16.2, P16.6, P16.7

Streams 28 Appendix I Character Streams (from old sun’s tutorial) A diagram of the classes for handling character streams