You are on page 1of 58

Streams: An Intro

Programs need to send/receive information from a variety of sources


file on a disk, If the application wants to receive/send data on a network, data, it creates a stream, and reads/write to data in memory, the streamanother program. data in

Types of data:
values, characters, image files sound files

InputStreams Hierarchy
InputStream
FileInputStream FilterInputStream

All these streams handle bytes


SequenceInputStream PipedInputStream ObjectInputStream

ByteArrayInputStream Public class

AbstractClass

extends

Streams: An Intro...
Create Streams
Add data java streams to stream read char(byte) from stream read char(byte) from stream

reading end

Writing end jv a a a va s t re am s source

InputStreams are those streams that have a reading end and the writing end is connected to a source which supplies data (e.g. a HARD DISK).

InputStream Class
class Name InputStream public abstract int read() methods int read(byte b[]) int read(byte b[], int off, int len) long skip(long n) int available() void close() void mark(int readlimit) void reset() boolean markSupported()

FileInputStream Class
class Name FileInputStream extends InputStream public FileInputStream(File) methods FileInputStream(FileDescriptor) FileInputStream(String) native int read() native long skip(long n) native int available() native void close() int read(byte b[]) int read(byte b[], int off, int len)

void mark(int)

int read()

int read(byte b[]) void reset()

long skip(long n) int available()

InputStream

int read(byte b[], int off, int len )

extends

void close()

int read(byte b[], int off, int len )

int read()
long skip(long n)

int read(byte b[]) FileInputStream void close() Native Methods

int available() abstract methods

Using FileInputStream...
Writing end

reading end
fis = new FileInputStream ();

system dependent resources

fis is the handle to the stream. One fis.read() will only read from

HD

can file read from this stream the only in the hard disk(HD)

Reading through Streams


Reading
open a stream (FileStream) while more information { read information } close the stream

Example
Read from file ( given as string in the command line ) then display contents on the console

Eg.FileInputDemo.java

OutputStreams Hierarchy
OutputStream
FileOutputStream FilterOutPutStream

PipedOutputStream ByteArrayOutputStream Public class ObjectOutputStream

AbstractClass

extends

OutputStream Class
class Name OutputStream public abstract void write(int); methods void write(byte[]); void write(byte[], int, int); void flush(); void close();

FileOutputStream Class
class Name FileOutputStream extends OutputStream public FileOutputStream(String); methods FileOutputStream(String,boolean); FileOutputStream(File); FileOutputStream(FileDescriptor); native void write(int); native void close(); void write(byte[]); void write(byte[], int, int); FileDescriptor getFD();

FileOutputStream...
reading end

writing end

system dependent resources

fos = new FileOutputStream();

fis.write() will only write to the

HD

file in the hard disk(HD)

Writing through Streams


Writing Open a stream (FileStream) while more information { write information } Close the stream

Example
Read form the console and Write it to a file (given as string in the command line).

Eg: FileOutputDemo.java

Class File
Uses of File class :
To extract information about files and directories of the local file system construct an object and use its methods to obtain information about the files/dirs on the local file system

Class java.io.File
class Name File public File (String thePath) methods File (String , String fname) File (File dir, String fname) String getAbsolutePath() String getCanonicalPath() boolean exists()/ canRead()/canWrite() long length()/lastModified(); boolean isFile()/isDirectory() boolean delete()/ renameTo(File)

Exercise
Write an application in java to display list of the directories or file contents of the specified path Textfield should be present at the top, in which we can specify the file path. Once the file/dir in the textfield is Eg FileTest.java specified. It should display info about the same in a textArea which is present

ByteArrayOutputStreams
application

boas

ByteArrayOutputStream baos=new ByteArrayOutputStream(); baos.write(int) // retrieve data from stream

byte b[] = baos.toByteArray();


143 54 23 93 155 length=5

ByteArrayOutputStream
Internal storage

ByteArrayInputStream
application 143 54

bais

ByteArrayInputStream bais=new ByteArrayInputStream(byte[]); S.o.p(baos.read()) S.o.p(baos.read())

ByteArrayInputStream Internal storage 143 54 23 93 155

protected InputStream in Implements all methods by calling the methods of the stream using handle in

public int read() throws IOException { InputStream return in.read();} interface DataInput

FilterInputStream

buffers input
BufferedInputStream LineNumberInputStream give line nums for chars:deprecated

write primitive java data types

DataInputStream

PushbackInputStream
allow bytes to be sent back to stream

InputStreams
Streams available and their functionality application application
FileInputStream ByteArrayInputStream

Hard Disk

Array of bytes

BufferedInputStream
application

bis

BufferedInputStream bis=new fis BufferedInputStream (fis); BufferedInputStream bis.read() FileInputStream Hard Disk

Require a parameter

FileInputStream fis=new FileInputStream another input stream as (test.dat);

E.g BufferedTextInputTest.java

BufferedInputStream Class
class Name BufferedInputStream extends FilterStream public BufferedInputStream(InputStream) methods BufferedInputStream(InputStream,int) int available() long skip(long n) Allows the use of mark, reset and void close() other methods on void mark(int) the inputstream void reset() int read(byte b[]) int read(byte b[], int off, int len)

Example

Read one fourth from file ( given as string in the command line ), and then display contents on the console. Reset it and then display the first one fourth of the Eg: TestBufferedStream.java contents again on the console.

DataInput boolean readBoolean() float readFloat() long readLong() short readShort() String readUTF() double readDouble() int readUnsignedByte() DataInputStream int readInt() int read(byte b[])

char readChar()
int read(byte b[], int off, int len ) byte readByte() String readLine()

int readUnsignedShort()

DataInput/OutputStreams
Read and write primitive data types in bit streams (actually stored as bytes) read and write in a machine independent way Data must be written and read in the same order

DataInput/OutputStreams
FileInputStream fis=new FileInputStream (testdata.dat); FileOutputStream fos=new FileOutputStream (testdata.dat); DataOutputStream dos=new DataOutputStream (fos); DataInputStream dis=new DataInputStream (fis); System.out.println(dis.readBoolean()); dos.writeboolean(true); dos.close(); fos.close();

Information stored internally as bit/byte Internal information not available to programmer HD

Example

Write a program to write the following information to a file named testItem.dat (items separated by tabs)

25.99 345.32

12 6

Tennis racket T-shirts

Write a second program to read and display the above information from the file testItem.dat

PrintStream
Deprecated use PrintWriter instead

Class System
An uninstantiable System class that provides a lot of important methods (all static) and references for other objects
InputStream in OutputStream out OutputStream err exit() gc() arrayCopy getProperties

Reading from Keyboard


A handle to the Keyboard data is given to the user as a InputStream (System.in) Programmer needs to encapsulate it with higher level streams to obtain and process inputs Use reader to trap characters, and then process them depending as to what the application requires

application br
BufferedReader br=new BufferReader( new InputStreamReader(System.in) ); String str = br.readLine() //process to obtain an integer int i = Integer.parseInt(str);

Operating System

Control returns after user Eg: KeyInput.java presses enter key

Redirecting Output to File


Use setOut(OutputStream ) of class System to set the output stream of the app consequent commands to print() and println() are set to that stream that was passed to setOut

Normal Application
application out
//write to System.out
System.out.println(java class);

Operating System

application

out

out

FileOutputStream fos = new FileOutputStream(temp.log); PrintStream ps = new PrintStream(fos); System.setOut(ps); //write to System.out

System.out.println(java class);

Operating System

Changing the output stream of the application

HD

Example
If the user gives a filename at the command prompt, then the application will redirect output to that file, and also to the console if the user does not give a filename, the application will write only to the console instead Eg: RedirectOutput.java of directing data to the file

Streams Heirarchy
Reader
BufferedReader StringReader

PipedReader All these streams handle chars CharArrayReader InputStreamReader FileReader FilterReader PushbackReader
AbstractClass

Public class

extends

Streams Heirarchy
Writer
BufferedWriter StringWriter PipedWriter FilterWriter PrintWriter
AbstractClass

CharArrayWriter OuputStreamWriter FileReader

Public class

extends

RandomAccessFile
Implements DataOut and DataInput It Supports both Reading and writing to a file Constructors: RandomAccessFile(File file, String mode) RandomAccessFile(String name, String mode) The mode argument must either be equal to "r" or "rw", indicating that the file is to be opened for input only or for both input and output, respectively.

RandomAccessFile...
Methods:
long getFilePointer() Returns the current offset in this file.
long length() Returns the length of this file. void seek(long pos) Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.

void write(int b) Writes the specified byte to this file

Example
E.g TextIOTest.java ( Writer and RandomAccessFile )

E.g ReadStream.java ( Readers & Writers using Applets )


Eg:TestIOTest.java Eg ReadStream.java

Object Serialization
Converting the state of an object into a serial information (binary / bytes). Uses
Information can be sent over the network to be reconstructed at the other end (rmi) stored in a hard disk as a file, and the object state can be reconstructed much after the object has been removed from memory (i.e persistence)

Serializing Java Objects


Object serialization is achieved through ObjectInputStream and ObjectOutputStream
ObjectOutputStream is used to write to a stream ObjectInputStream is used to read from stream

class Name publicclass ObjectOutputStream methods ObjectOutputStream


ObjectOutputStream(OutputStream) final void writeObject(Object) write(byte[]); write(byte[], int, int) If you want to store the object state to a file, pass a writeBoolean(boolean) writeByte(int); writeBytes(String) FileInputStream handle writeChar(int); writeChars(String) here writeFloat(float); writeDouble(double) writeFields() write(int); writeInt(int) writeShort(int); writeLong(long) writeUTF(String); defaultWriteObject(); flush(); close()

Serializing Java Objects


Steps to serialize object data to a stream
If you want create an ObjectOutputStream to store the object state to a file, pass a create object to be serialized (e.g.. String FileInputStream handle here object) use the writeObject method with the object reference as a parameter

ObjectOutputStream oos = new OOS(); String st = new String(java serialization); oos.writeObject(st);

Serializing Java Objects


Steps to deserialize object state from ObjectInputStream ois = new OIS(); String st; stream (reading from the stream)
create an ObjectInputStream define type of handle for object Methods for input stream match use the readObject method which returns the methods in to the serialized object as outputstream the object reference an java OutputStream Object referenceInputStream typecast it back to the correct object type writeChar(char) char readChar() sequence of reading is same as that of writing
st = (String)ois.readObject();

Example
Write a program to store a string followed by a vector that stores james bond, 007, last line into a file objdata.txt (this example shows serializing the String object and the Vector object) Write a second program to read the file objdata.txt, and display the contents on the console

Eg: OOSPoint. java

Serializing Custom Classes


An object (written by the programmer) becomes serializable by implementing the Serializable interface (java.io package, and it contains no methods) Serialization is then taken care of by the defaultWriteObject(...) method of the ObjectOutputStream class Deserialization is similarly taken care of by the defaultReadObject(...) of the ObjectInputStream class

Example
Consider the Point class
make it Serializable (i.e implements the Serializable interface)

Write another class file SerialPoint.java to store the Point information to a file Read the information from the file and Eg: Point.java Eg:SerialPoint.java display values stored in point object from file

Serializing Custom Classes


If you want to add additional information to the stream (to stream / file), then one has to override the writeObject() method in their class with signature
private void writeObject(ObjectOutputStream) throws IOException; you will need to call the defaultWriteObject to serialize the data of your class after that you can add whatever data you want to be serialized alongwith the class

Serializing Custom Classes


In such cases they will have to read data in the same reverse order and override the readObject() method in their class
private void readObject(ObjectInputStream stream) throws IOException;

Example
Write some String after serializing the object , read the info stored after de-serializing in a separate variable (initially set to null)
Eg: SerialNewPoint.java
Eg: NewPoint.java

File Channel
A channel for reading, writing, mapping, and manipulating a file. This Slid concentrates on file locking mechanisms. FileChannel.lock() Acquires an exclusive lock on this channel's file.

FileChannel.lock(long position, long size, boolean shared) Acquires a lock on the given region of this channel's file. The above methods return a FileLock Object.
Method : FileLock.release()

FileLockDemo.java

Exercise (contd)
16. A need to persist the data has now arisen as the client observes that the development team is either getting the data from the console or is having it stored as string attributes in the programs. The client wishes that the data should be persisted and reused by any other programs, as well. Hence, store the data in the Collection into a file. Implement methods to read/write the data to/from the given file. The access methods should be synchronized

Exercise (contd)
Apart from persisting data, the input and output operations should not be through the console. Appropriate GUI should be designed to enter the data and show the computed results. Write the required GUI programs which address the functionality of the programs written earlier, using the console for the input/output.

You might also like