Introduction to Computation and Problem Solving Class 29: Introduction to Streams Prof. Steven R. Lerman and Dr. V. Judson Harward.

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 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.
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
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.
COMP201 Java Programming Topic 5: Input and Output Reading: Chapter 12.
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.
Simple Java I/O Part I General Principles. 2 Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
Overview of Java I/O. Stream A Program often needs to read/write information from/to outer source/destination. Outer source/destination can be : –A File.
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.
1 Text File I/O Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l.
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.
1 Streams Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l Writing.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
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.
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.
Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.) –it acts as.
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.
Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams F Text Input and Output on the Console.
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,
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.
MIT AITI 2003 Lecture 15 Streams Input and Output data from/to other sources.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
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.
L5: Input & Output COMP206, Geoff Holmes and Bernhard Pfahringer.
Two Ways to Store Data in a File  Text format  Binary format.
CIS 270—App Dev II Big Java Chapter 19 Files and Streams.
A stream is a sequence of data. A stream is a flowing sequence of characters.
Streams and File I/O Chapter 9. Outline Overview of Streams and File I/O Text-File I/O Using the File Class Basic Binary-File I/O Object I/O with Object.
Lecture 5 I/O and Parsing
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
Chapter 9 1 Chapter 9 – Part 2 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.
– 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.
Chapter 15: Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams F Parsing Text Files F Random.
Chapter 15: Input and Output
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.
Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that.
1 Putting Streams to use. 2 Stream Zoo C++ gives you istream, ostream, iostream, ifstream, ofstream, fstream, wistream, wifstream, istrsteam… (18) Java.
GENERICS AND FILE HANDLING Saumya Srivastava (977934) Divyangana Pandey (977790) Shubhi Saxena (978108) Arka Das (962969) AHD05/15-16 AJA 21.
Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Announcements/Reminders l Project 6 due on Thursday March 31 (3 weeks)
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 I/O 1. Java I/O (Input and Output) is used to process the input and produce the output based on the input. The java.io package contains all the classes.
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
Fundamental of Java Programming
IO in java.
Lecture 8: I/O Streams types of I/O streams Chaining Streams
IO in java.
Chapter 17 Input and Output
OO Design and Programming II I/O: Reading and Writing
Object Writing in files
I/O Basics.
Streams and File I/O Chapter 9 Chapter 9.
David Davenport Spring 2005
Presentation transcript:

Introduction to Computation and Problem Solving Class 29: Introduction to Streams Prof. Steven R. Lerman and Dr. V. Judson Harward

Goals Just as Java® has a modern approach to error handling inherited from C++, Java® communicates with the outside world using another C++ inspired technique called streams. In this session, we will: Look at the classic stream code to read a file. Examine Java®'s architecture of stream classes Learn how to parse simple text input.

JFileViewer JFileViewer is a small demonstration program that reads in reads in a file and puts it up in a text area. It is composed of two classes: – JFileViewer:main() and main loop – JTextViewer: the (rudimentary) GUI

JFileViewer,core try block (in English) try { open a stream from the file while there is more data read it append it to our GUI display close the file } catch any I/O errors

JFileViewer, core try block (in Java®) try { FileReader in = new FileReader( args[ 0 ] ); char [] buf = new char[ 512 ]; int nread; while( ( nread = in.read( buf ) ) >= 0 ) { view.append( new String( buf, 0, nread ) ); } in.close(); }catch ( IOException e ){ handleErr( e ); }

Traditional I/O The traditional approach uses different schemes depending on the type of the source or destination, e.g., – keyboard input – screen output – files – interprocess pipes – network sockets

Java® I/O Java®’s preferred approach is to handle I/O using streams (pioneered in C++) Think of a stream as a data hose connecting the program to the outside world. It hides the details of the external data source or destination. Java® allows you to treat some I/O distinctively, e.g. RandomAccessFile

Input vs Output Streams Streams are unidirectional An input stream controls data coming into the program from some source An output stream controls data leaving the program for some destination If you want to read and write the same destination, you use 2 streams

Streams and I/O Channels Usually the other end of a stream leads to or arises from a platform- specific media service, for instance, a file system Input Stream File System Program Output Stream File System

Java® Stream Classes Java® provides – a set of abstract stream classes that define the stream interfaces for different kinds of streams: InputStream: reads bytes OutputStream: writes bytes Reader: reads chars Writer: writes chars – a hierarchy of stream implementations: that are tailored for a particular data source or destination, e.g., FileReader reads chars from a file that add functionality to a preexisting stream (filter streams), e.g., BufferedReader

What Streams Share Java® Streams are FIFO queues – Streams deliver information in the order it was inserted into the underlying channel Basic Java® streams only provide sequential access without rewind, backup, or random access

Coupling Streams Java® streams may be combined by using one stream as a constructor argument to another This is usually done to add functionality and/or convert the data Stream pipelines are constructed – from the data source to the program or – from the data destination back to the program

Stream Pipeline, I

Stream Pipeline, II A FileInputStream reads bytes from a file An InputStreamReader converts a byte stream to characters – A FileInputStream coupled with an InputStreamReader equals a FileReader A BufferedReader buffers a character stream for efficiency, and alows you to read line by line A StreamTokenizer parses a character stream into tokens

Constructing the Pipeline FileInputStream f = new FileInputStream( path ); InputStreamReader i = new InputStreamReader( f ); BufferedReader b = new BufferedReader( i ); StreamTokenizer t = new StreamTokenizer( b );

The 3 Flavors of Streams In Java®, you can read and write data to a file: – as text using FileReader and FileWriter – as binary data using DataInputStream coupled to a FileInputStream and as a DataOutputStream coupled to a FileOutputStream – as objects using an ObjectInputStream coupled to a FileInputStream and as an ObjectOutputStream coupled to a FileOutputStream

Text Streams: Readers FileReader methods: – public FileReader(String name) throws FileNotFoundException – public FileReader(File f) throws FileNotFoundException – public int read(char[] cbuf) throws IOException – public int read() throws IOException – public void close() throws IOException BufferedReader methods: – public BufferedReader(Reader in) – public String readLine() throws IOException

Text Streams: Writers FileWriter methods: – public FileWriter(String name) throws IOException – public FileWriter(File f) throws IOException – public void write(char[] cbuf) throws IOException – public void write(String s) throws IOException – public void write(int c) throws IOException – public void close() throws IOException – public void flush() throws IOException BufferedWriter methods: – public BufferedWriter(Writer in) – public void newLine() throws IOException

DataInputStream Methods – public DataInputStream(Input Stream in), e.g. DataInputStream d = new DataInputStream( new FileInputStream( "f.dat" )); – public boolean readBoolean() throws IOException – public int readInt() throws IOException – etc plus all the standard InputStream methods: – public int read() throws IOException – public int read(byte[] b) throws IOException – public int read(byte[] b, int off, int len) throws IOException – public void close() throws IOException

ObjectOutputStream Methods – public ObjectOutputStream(OutputStream out), e.g. ObjectOutputStream d = new ObjectOutputStream( new FileOutputStream( "f.dat" )); – public void writeBoolean(boolean b) throws IOException – public void writeInt(int i) throws IOException, etc – public void writeObject(Object obj) throws IOException plus all the standard OutputStream methods: – public void write(int i) throws IOException – public void write(byte[] b) throws IOException – public void write(byte[] b, int off, int len) throws IOException – public void close() throws IOException

Serialization ObjectInputStream and ObjectOutputStream depend on a technique called object serialization. If you want to write out an object instance on a stream, you must write out the object's fields. The fields can contain native types or references to other object instances. You can recursively write out those references to contained instances. Eventually you can serialize any object instance (from a class that implements Serializable) into fields of native types

Serialization Diagram Live ObjectsSerialized

Serializing a List

StreamTokenizer Java® supplies a special class called StreamTokenizer that accepts a Reader as a constructor argument. It breaks the input character stream into tokens, sequences of 1 or more contiguous characters that "belong" together. The user accesses these tokens by calling the nextToken() method, which always returns an int representing the type of the next token: – word, – number, – end of file (EOF), – end of line (EOL, optional), and – otherCharacter, returned as int value of the 16 bit character code

StreamTokenizer, 2 When a StreamTokenizer recognizes a word, the public member sval contains the String representing the word. When a number token is recognized, public member nval contains its value. StreamTokenizer also ignores whitespace (blanks and tabs) and C, C++, and Java® style comments by default. StreamTokenizer instance methods can change the definition of “word” or “number” and can turn on or off features like ignoring comments.

JPolygonPlotter PolygonPlotter is a sample program that illustrates how to handle formatted input. It reads a data file that describes a set of polygons and then plots them in a window. The command line accepts 3 arguments: width and height of the display window and the name of the data file.

JPolygonPlotter, 2 The data file consists of a series of polygon definitions separated by blank lines. Each polygon definition consists of lines containing two integers each, an x-and a y-coordinate. The program checks for improperly formatted input. If it can not make sense of what it is reading, it throws an DataFormatException. In the catch clause it sends an error message to the console identifying where in the input file it got confused.

JPolygonPlotter, main() public class PolygonPlotter { private static PolygonViewer view; private static int width = 0; private static int height = 0; private static FileReader fileRdr; public static void main( String[] args ) {... view = new PolygonViewer( width, height ); readPolygons( args[ 2 ] );... }

JPolygonPlotter, readPolygons() private static void readPolygons( String f ) { try { fileRdr = new FileReader( f ); BufferedReader bufRdr = new BufferedReader( fileRdr ); StreamTokenizer tokens = new StreamTokenizer( bufRdr ); tokens.eolIsSignificant( true ); main loop bufRdr.close(); } catch ( IOException e ) { handleErr( e ); } }

JPolygonPlotter, readPolygons() main loop in English try { get a token while we haven't reached the end of file if line is blank, skip it else if the line starts with a number extract the next polygon from the data else throw a DataFormatException } } catch ( DataFormatException e ) { write an error message and exit }

JPolygonPlotter, readPolygons() main loop try { tokens.nextToken();while ( tokens.ttype != StreamTokenizer.TT_EOF ){ if ( tokens.ttype == StreamTokenizer.TT_EOL ) { // if line is blank, skip it tokens.nextToken(); } else if ( tokens.ttype == StreamTokenizer.TT_NUMBER ) { // if line starts with a number, parse polygon view.addPolygon( extractPolygon( tokens )); } else throw new DataFormatException(); } } catch ( DataFormatException e ) { System.err.println( "Can't read lineno " + tokens.lineno() + "." ); System.exit( 1 ); }

JPolygonPlotter, extractPolygons() private static Polygon extractPolygon( StreamTokenizer t ) throws DataFormatException, IOException { Polygon p = new Polygon(); do { int x = ( int ) t.nval; if ( t.nextToken() != StreamTokenizer.TT_NUMBER ) throw new DataFormatException(); inty = ( int) t.nval; y = height -y -1; if ( t.nextToken() == StreamTokenizer.TT_EOL || t.ttype == StreamTokenizer.TT_EOF ) { p.addPoint( x, y ); } else throw new DataFormatException(); } while ( t.ttype == StreamTokenizer.TT_EOL && t.nextToken() == StreamTokenizer.TT_NUMBER ); return p; }