1 Streams Chapter Nineteen. 2 What are streams? l Input and Output for example from the keyboard (a standard input device) or the CRT (a standard output.

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.
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.
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
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.
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.
Files Files are used to store long term data. –Typically referred to as persistent data. –A file is a group of related records. –A list of friends addresses.
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.
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.
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.
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.
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.
5-Oct-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Streams and Files Maj Joel Young.
Very Brief Introduction to Java I/O with Buffered Reader and Buffered Writer.
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
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.
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.
Copyright © Curt Hill Java I/O Flexibility and Layering.
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.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
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.
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.
1 Java b Object Oriented b Powerful b Interpreted b Portable b Platform independent b filename.java b filename.class(bytecode)
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.
Copyright(c) Systems and Computer Engineering, Carleton Univeristy, * Object-Oriented Software Development Unit 13 I/O Stream Hierarchy Case.
– 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.
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.
Chapter 15: Input and Output
Company Input/Output Stream –. Input/Output Stream Data Program Input Stream Output Stream.
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.
Exception Handling, Reading and Writing in Files, Serialization, Exceptions, Files, Streams, File Readers and Writers, Serializable SoftUni Team Technical.
Prepared by Dr. Jiying Zhao University of Ottawa Canada.
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.
Agenda Socket Programming The OSI reference Model The OSI protocol stack Sockets Ports Java classes for sockets Input stream and.
Java Programming: Advanced Topics 1 Input/Output and Serialization.
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.
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
Lecture 8: I/O Streams types of I/O streams Chaining Streams
BINARY I/O IN JAVA CSC 202 November What should be familiar concepts after this set of topics: All files are binary files. The nature of text files.
Java Text I/O CS140 Dick Steflik. Reader Abstract super class for character based input Subclasses: – BufferedReader – CharArrayReader – FilterReader.
Exception Handling, Reading and Writing in Files, Serialization,
Ch14 Files and Streams OBJECTIVES
Object Writing in files
OBJECT ORIENTED PROGRAMMING II LECTURE 21_1 GEORGE KOUTSOGIANNAKIS
I/O Basics.
Chapter 17 Binary I/O 1.
Chapter 17 Binary I/O Dr. Clincy - Lecture.
null, true, and false are also reserved.
OBJECT ORIENTED PROGRAMMING II LECTURE 11_1 GEORGE KOUTSOGIANNAKIS
Files and Streams in Java
David Davenport Spring 2005
Presentation transcript:

1 Streams Chapter Nineteen

2 What are streams? l Input and Output for example from the keyboard (a standard input device) or the CRT (a standard output device) or I/O with files. l TOPICS: l Input streams how to create, use, detect end of them and filtered input streams l Output streams mostly opposite of input

3 Some terms: l Pipe - an uninterpreted stream of bytes. Communication between programs are for reading/writing to peripheral devices. The stream can come from any source your disk or the internet as examples l UNIX an operating system (CCAC uses a UNIX server for its internet server) it will be the location of your web pages called a point server.

4 InputStream and OutputStream are java abstract classes...See java.io (Appendix B). Text starts at the top of the tree and works down All program sequences this chapter need Import java.io.*;

5 Input Streams l Methods used are “throw IOExceptions” –subclass “Exception” l You must catch an IOException (or pass it along) l The abstract Class InputStream - You are the destination of the bytes - do not care where they came from

6 l read( ) “block” - wait for the input requested [ a good chance to use multi threading while you wait ] l InputStream s = getAnInputStreamFromSomewhere( ); l byte[] buffer = new byte[1024]; // any size l if(s.read(buffer) ! = buffer.length) l System.out.println(“I got less than I expected.”); l //In this chapter an import java.io.*should be at top of all programs

7 What the last program will do. Either it will fill the entire buffer or it will return thenumber of bytes read into the buffer. l Another possible use of read( ) l s.read(buffer, 100,300); // start with an offset (up from beginning 100 bytes) and then go for 300 bytes.

8 l Example: l public int read(byte[] buffer) throws IOException { l return read(buffer, 0, buffer.length); } l InputStream s = getAnInputStreamFromSomewhere( ); l byte b; int byteOrMinus1; l while ((byteOrMinus = s.read( )) != -1) { l b = (byte) byteOrMinus1;.... //process the // byte b }... reached end of stream l NOTE the read( ) method return an integer

9 skip( ) how it can be used - kind of like a read( ) l if (s.skip(1024) ! = 1024) l System.out.println(“I skipped less that I expected.”); l public long skip(long n) throws IOException { l byte[] buffer = new byte [ (int) n]; l return read(buffer); } // NOTE (int)

10 available( ) - How many bytes are in the stream? l if (s.available( ) < 1024) l System.out.println(“Too little is available right now.”); l problem: way some streams always return zero when asked and because of multithreading - no need for available( )

11 mark( ) and reset( ) l Have you ever marked your way (or some line of code in a trace?) I am Here NOW...later reset(ing) back to the original position. You set the bytes you can go before reset(ing): l InputStream s = getAnInputStreamFromSomewhere( ); l if(s.markSupported( )) //read for awhile l s.mark(1024);... s.reset( ); } else... {... }

12 close( ) l Some systems if you do not close files they just stay open and are at the mercy (do not count on mercy) of anyone on the system - which may be the internet. l A good way of making sure: l InputStream s = alwaysMakesANewInputStream( ); l try {...// use s to your hearts content l } finally { s.close( ); }

13 l even better l InputStream s = tryToMAkeANewInputStream( ); l if( s != null) { try {... } // just in case a null was returned l finally { s.close( ); } }

14 ByteArrayInputStream l Purpose to create a stream from an array of bytes // kind of the reverse of what previous slides have been discussing: l byte[] buffer = new byte[1024]; l fillWithUsefulDate(buffer); l InputStream s = new ByteArrayInputStream(buffer); l like read( ) // has a form with offset and length

15 l InputStream s = new ByteArrayInputStream(buffer, 100, 300); l Creates a Stream... l available( ) reset( ) can be used too.

16 FileInputStream l InputStream s = new FileInputStream (“/some/path/and/filename”); l This MAY cause security violations (applets reading or attempting to read files set off all kinds of ALARMS (sometimes) l You should keep it short: The user may assign a single file/directory with permission attached to it

17 You can create a stream from a previously opened file descriptor: l int fd = openInputFileInTraditionalUNIXWays( ); l InputStream s = new FileInputStream(fd); l Some additional tricks: l FileInputStream aFIS = new FileInputStream(“aFIleName”); l int myFD = aFIS.getFD( ); l /* aFIS.finalize( ); */ // will call close( )

18 FilterInputStream l The general idea a “filter” or pass through l InputStream s = getAnInputStreamFromSomewhere( ); l FilterInputStream s1 = new FilterInputStream(s); l FilterInputStream s2 = new FilterInputStream(s1); l FilterInputStream s3 = new FilterInputStream(s2);...s3.read( )...

19 How the last slide (code) works l the read s3 passes onto s2 inturn to s1 and finally to s. s is asked for the bytes l also called “chaining” l Example of filters (ie. little rocks go through big ones do not) l pass through account...

20 BufferedInputStream l one of Most valuable: reads “chunks” l A buffer is memory for example that is used as an area that “spoon feeds” a peripherial device at its speed not full speed of CPU. l handels mark( ) reset( ) properly l and you can mark/reset files (which are streams....of course....at least the data in them can be: l InputStream s = new BufferedInputStream(new FIleInputStream(“foo”));

21 DataInputStream l A general purpose interface (you can use it in the classes you create) l DataInputStream and RandomAccessFile l implement. l The DataInput Interface: SEE PAGE 385 for all the methods this interface defines: l General form: read....( ) l boolean, byte,short,int(signed/unsigned, l char,long,float,double,String(Line/UTF l ALL throw IOExceptions

22 Example of last slide l DataInputStream s = new DataInputStream(getNumericInputStre am( )); long size = s.readLong( ); l while (size >0) { if (s.readBoolean( ) ) { l int anInteger = s.readInt( ); l int magicBitFlags = s.readUnsignedShort( ); l double aDouble = s.readUnsignedShort( ); l if ((magicBitFlags & ) ! = 0) { l... // hi bit set, do something}...//process } }

23 EOFException = end of file (stream) exception l DataInputStream s = new DataInStream(getAISFS( )); // abbreviation l try { while (true) { byte b = (byte) s.readByte( );..// process byte } catch l (EOFException e) { //... reached end of //stream l }

24 LineNumberInputStream: l Streams with line numbers (listings etc.) mark( ) it and reset( ) it later l a variable called aLNIS (line number input file/stream) is checked l The system print “did line number + aLNIS.getLineNumber( ));

25 PushbackInputStream l a look ahead (C/C++ think escape sequences) OK we found a \ look ahead see if next character is a legal escape character if OK do “it” else ERROR caused l \n legal escape sequence in Java C C++

26 l //unread( ) does the “pushback” (i.e. read a character - then go back one after “you” figure what to do next: Example l public class SimpleLineReader { l private FilterInputStream s; l public SimpleReader(InputStream anIS) { l a = new DataInputStream(anIS); } l public String readLine( ) throws IOException { char[] buffer = new char[100]; byte thisbyte; // ONLY 100

27 l try { // note next line “loop:” = top of loop l // first example in text l loop: while (offset < buffer.length) { l switch (thisByte = (byte) s.read( ); l // good quiz question why (byte) in last line l case ‘\n’: break loop; l case ‘\r’ : byte nextByte = (byte) s.read( ); l if (nextByte ! = ‘\n’) { –if (!( s instanceof PushbackInputStream)) { –s = new PushbackInputStream(s) ; } –( (PushbackInputStream) s).unread(nextByte);

28 l if (nextByte ! = ‘\n’) { –if (!( s instanceof PushbackInputStream)) { –s = new PushbackInputStream(s) ; } –( (PushbackInputStream) s).unread(nextByte); } // Note unread( ) l break loop; l default: buffer[offset++] = (char) thisByte; l break: } } } l catch (EOFException e) { if (offfset = = 0) l return null; } return String.copyValueOf(buffer, 0, offset); } }

29 PipedInputStream / PipedOutputStream two way Communication between threads l How to Concatenate two Streams: l Good bye ---> Goodbye l InputStream s1 = new FileInputStream(“theFirstPart”);

30 l InputStream s2 = new FileInputStream”theRest”); l InputStream s = new SequenceInputStream(s1 s2); l s.read( )... reads from s the combined stream l The same idea can continue to work with more than two Strings...first InputStream the first two then the third with the result of the combination of S1 and S2... and that could go on...and on...

31 StringBufferInputStream l based on an array of characters: –If a buffer was filled with “Now is the time for all good men to come to the aid of their party” l String buffer = “ Now is the time...etc”; l InputStream s = new StringBufferInputStream(buffer) l Acts like ByteArrayInputStream

32 Output Streams Or... We have ways of making you talk.... l Who you are really talking to is irrelevant l You control the vertical You control the horizontal...Just kidding...You actually control the bytes: write( ) Example: l OutputStream s = getAnOutputStreamFromSomewhere( ); l byte[] buffer = new byte[1024]; //any size l fillInData(buffer); s.write(buffer); OR l s.write(buffer, 100, 300); // put it exactly...

33 Do not forget to flush( ) and close( ) That sounds awful...but it may NOT be a bad thing... l flush( ) = send your output through some buffer l close( ) = release resources that may have been reserved for your behalf

34 ByteArrayOutputStream directs an output stream INTO an array of bytes l OutputStream s = new ByteArrayOutputStream( );....s.write(123); l You can add an initital capacity by: l OutputStream s = new ByteArrayOutputStream(1024 * 1024); l Stream can be output (re-directed) to another stream

35 FileOutputStream USE: attach the stream to file(s) l OutputStream s = new FileOutputStream(“/some/path/and/f ilename”); l CAN cause security violations on some systems

36 FilterOutputStream l A pass-through abstract class l (a pass through account is supposed to be temporary - several checks deposited to it one written out) l like FilterInputStream just passes requests for a write( ) up a chain - sme minor processing may be done: s3.write(123) in example passed to s2, s2 and finally s

37 BufferedOutputStream l Acts as a cache (pronounced cash $ ) l decouples (breaks down) chunks rate/size blocks into more efficient data size for peripherals/files/or the net l OutputStream s = new BufferedOutputStream( new FileOutputStream(“foo”)); l flush( ) // is then possible

38 DataOutputStream Similar but opposite side on coin of “DataInput” interface l DataOutputStream and RandomAccessFile implement - general purpose l The DataOutput Interface covers: l ( int i), (byte[] buffer) (byte[] buffer, int offset, int length) l writeBoolean, Byte, Short, Char, Int, Long, Float, Double, Bytes, Chars, and writeUTF l All throw IOExceptions

39 Quick example: l DataOutputStream s = new DataOutputStream(getNumericOutput Stream( ) ); long size = getNumberOfItemsInNumericStream( ); l s.writeLong(size); l for (int i = 0; i < size; ++i) { –if (shouldProcessNumber(i) ) {

40 l s.writeBoolean(true); l s.writeInt(theIntegerForOtemNumber(i) ); l s.writeShort(theMagicBitFlagsForNume r(i)); s.writeDouble(theDoubleForInemNum ber(i)); } else l s.writeBoolean(false); } l THIS example is the exact inverse of DataInput both communicate an array of structures primitive types accross any stream. (SLIDE 22)

41 l Processing a file (read/process a record/write out to a different file) l DataInput aDI = new DataInputStream(new FileINputStream(“source”)); l DataOutput aDO = new DataOutputStream(new FileOutputStream(“dest”)); l String line; l // all the major variables aDI, aDO, line

42 l while ((line = aDI.readLine( ) ) ! = null) { l // Not E.O.L. yet l StringBuffer modifiedLine = new StringBuffer(line); l...// do some process l aDO.writeBytes(modifiedLine.toString( ) );} aDI.close( ); aDO.close( ); l // remember to close....

43 l //just a few lines more... l try { –while(true) { –byte b = (byte) aDI.readByte( ); –... // process b here –aDO.writeByte(b) } l finally { aDI.close; aDO.close( ); } l OR... try { while (true) aDO.writeByte(aDI.readByte( ) );} l finally { aDI.close( ); aDO.clase( ); }

44 Streams you have already crossed... l System.out.print( ) l System.out.println( ) l System.err // not that anyone ever has err l System.in // input stream

45 See page 398 for all the choices of primitive type (some 23 examples) l // Just one here l public void printl(int i);

46 PipedOutputStream - along with PipedInputStream supports piped connections between two threads l PipedInputStream sIN = PipedInputStream( ); l PipedOutputStream sOut = PipedOutputStream(sIn); // that s - In l not //sin....One thread writes to sOut the other reads from sIn

47 Related Classes l File // tells about attributes of specific file l RandomAccessFile // provides “seek( )ing l StreamTokenizer class // tokens ie words seperated by any thing you decide