Chapter 6

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 44

Chapter 6

Streams and Files IO


Marks -12
Chapter Goals
• To be able to read and write text files
• To become familiar with the concepts of text
and binary formats
• To understand when to use sequential and
random file access
Introduction
• Variables and arrays are used for storing
data inside the programs.
• This approach poses the problems-
• The data is lost when program is
terminated.
• It is difficult to handle large volume of
data using variables and arrays.
Introduction
File : A file is collection of related records
placed in a particular area on disk.
Record : A record is composed of several
fields.
Fields : A field is group of characters
Character : A Character in java is sequence
of Unicode characters.
Data Representation in java Files
Byte Byte

0 0 0 0 0 0 0 0 0 1 0 0 1 0 1 0
Unicode Character
J O h n Field 4 Characters

John 1001 70.50 Record 3 Fields

John 1001 70.50 File 4 Records


Lata 1002 57.50
Mani 1003 75.00
Viju 1004 82.50
Introduction
• File Processing
• Storing and managing data using
files is known as file processing.
• It includes
• Creating files,
• Updating files and
• Manipulation of data.
Concept of Streams
• In file processing, input refers to the flow of
data into a program and
• Output means the flow of data out of a
program.

Keyboard Screen

Mouse Printer
Java
Memory Program Memory

Disk Disk

Network Input Output Network


Concept of Streams
• Streams represent the ordered sequence of
data.
• A stream in java is a path along which data
flows (like river or pipe).
• It has source and destination.

-------------------------------------
-------------------------------------
------------------------------------- Stream
-------------------------------------
Streams
• Java Streams are classified in two basic types
• Input Stream
• Output Stream
• An Input Stream extracts data from the
source (file) and sends it to the program.

• An Output stream takes data from the


program and sends (i.e. writes) it to the
destination (file).
Input and Output Streams
• Streams can be used to filter data.
• One stream used to get raw data in binary format and
then use another stream in series to convert it to integers

Input
Reads
Source Program
Stream

Ouput
Writes
Program Destination
Stream
Stream Classes
• The java.io package contains number of stream
classes for processing all type of data.
• These classes are categorized in two groups
• Byte Stream classes
• Character Stream Classes
• Byte Stream classes handle I/O operations
on Bytes.
• Character Stream classes manage I/O
operations on Characters.
Java Stream Classes
Java Stream
Classes

Byte Stream Character


Classe Stream Classes

Input Stream Output Writer


Stream Reader
Classes Classes Classes Classes

Memory File Pipe Memory File Pipe


Byte Stream Classes
• Byte stream classes provide functional features
for creating and manipulating streams and files
for reading and writing bytes.

• The streams are unidirectional therefore java


provides two types of byte streams classes:
• Input stream classes and
• output stream classes.
Input Stream Classes
InputStream

ByteArray FileInputStream SequenceInputStream


InputStream
ObjectInputStream PipedInputStream
FilterInputStream

BufferedInputStream DataInputStream PushbackInput


Stream
DataInput
Hierarchy of Input Stream Classes
Input Stream Classes
• The Super class InputStream is abstract class.
• It defines methods for performing functions such
as –
• Reading Bytes
• Closing streams
• Marking position in streams
• Skipping Ahead in stream
• Finding the number of bytes in a stream
InputStream Methods
read() -: Reads a byte from input stream.

read( byte b[]) :- Reads an array of bytes into b.

read( byte b[], int n, int m) :- Reads m bytes into b


starting from nth byte

available( ) :- Gives number of bytes availble in the input

skip( n) :- Skips over n bytes from the input stream

reset( ) :- Goes back to the beginning of the stream

close( ) :- Closes the input stream


InputStream Methods
• The DataInputStream Class extends
FilterInputStream and implements interface
DataInput.
• So additional methods are available:
InputStream
Methods
 Reading
• read() methods will block until data is available to be
read

• two of the three read() methods return the number of


bytes read. -1 is returned if the Stream has ended.

• throws IOException if an I/O error occurs. This is a


checked exception
Output Stream Classes
 There are 3 main read methods:

 int read()
 Reads a single character. Returns it as
integer
 int read(byte[] buffer)
 Reads bytes and places them into buffer
 returns the number of bytes read

 int read(byte[] buffer, int offset, int length)


 Reads up to length bytes and places them
into buffer
 First byte read is stored in buffer[offset]
 returns the number of bytes read
Creating an
InputStream

ByteArrayInputStream:
 Constructor is provided with a byte array.
 This byte array contains all the bytes provided
by this stream
 Useful if the programmer wishes to provide
access to a byte array using the stream
interface.

FileInputStream:
 Constructor takes a filename, File object or
FileDescriptor Object.
 Opens a stream to a file.

FilterInputStream:
Byte-Oriented Output Stream
Classes
OutputStream

PipedOutputStrea
ByteArrayOutput FileOutputStream
Stream m

ObjectOutputStream FilterOutputStream

BufferedOutputStream DataOutputStream PrintStream

DataOutput
OutputStream Methods
Writing:
write() method writes data to the stream.
Written data is buffered.
Use flush() to flush any buffered data from the
stream.
throws IOException if an I/O error occurs. This
is a checked exception
There are 3 main write
methods:
 void write(int data)
Writes a single character
Note: even though data is an integer, data must be set
such that:
0 <= data <= 255

 void write(byte[] buffer)


Writes all the bytes contained in buffer to the stream

 void write(byte[] buffer, int offset, int length)


Writes length bytes to stream starting from
buffer[offset]
OutputStream Methods
 flush()
 To improve performance, almost all output
protocols buffer output.
 Data written to a stream is not actually sent until
buffering thresholds are met.
 Invoking flush() causes the OutputStream to
clear its internal buffers.
 close()
 Closes stream and releases any system resources.
Creating an
OutputStream
 OutputStream is an abstract class.
• Programmers instantiate one of its subclasses

 ByteArrayOutputStream:
• Any bytes written to this stream will be stored in a byte array
• The resulting byte array can be retrieved using toByteArray()
method.

 FileOutputStream:
• Constructor takes a filename, File object, or FileDescriptor object.
• Any bytes written to this stream will be written to the underlying
file.
• Has one constructor which allows for appending to file:
• FileOutputStream(String filename, boolean append)

 FilterOutputStream:
• Provides a basis for Output Filter Streams.
• Will be covered later in chapter.
import java.io.*;
public class CopyFile {
public void copyFile( String inputFilename, String outputFilename)
{ try {
FileInputStream fpin = new FileInputStream(inputFilename);
FileOutputStream fpout = new FileOutputStream(outputfilename);
byte buffer = new byte[8192];
int length = 0;
while ((length = fpin.read(buffer, 0, buffer.length)) > 0)
{
fpout.write(buffer, 0, length); }
fpout.flush();
fpout.close();
fpin.close();
}
catch (IOException x) {}}}
Character Stream Classes
Reader

PipedReader CharArrayReader StringReader

InputStreamReader
BufferedReader
FilterReader
FileReader
LineNumberReader PushbackReader
Reader class Methods
Reading
read() methods will block until data is available
to be read
two of the three read() methods return the
number of bytes read
-1 is returned if the Stream has ended
throws IOException if an I/O error occurs. This
is a checked exception
Reader class Methods
• There are 3 main read methods:
 int read()
Reads a single character. Returns it as integer

 int read(char[] buffer)


Reads bytes and places them into buffer
returns the number of bytes read

 int read(char[] buffer, int offset, int length)


Reads up to length bytes and places them into
buffer
First byte read is stored in buffer[offset]
returns the number of bytes read
Reader class Methods
close() method closes the stream
mark(int readAheadLimit) - marks the
current location
Parameter specifies number of characters which
can be read before the marks becomes invalid
ready() returns true if there is data to be read
from the stream
reset() returns the stream to its previously
marked location
skip(long n) skips over n bytes
Creating a Reader Object
Reader is abstract. Programmers instantiate
one of its subclasses.
BufferedReader
Reads text from the character input stream
Provides buffering to provide efficient reading
of characters, arrays and lines
CharArrayReader
Similar to ByteArrayInputStream
Constructor takes a character array. The
character array provides the characters for the
stream.
Creating a Reader Object
InputStreamReader
This class acts as a bridge from byte streams to
character streams
The InputStreamReader reads bytes from the
InputStream and translates them into characters
according to the specified encoding.

PipedReader
Similar to PipedInputStream
Connects to an Instance of PipedWriter
Creating a Reader Object
StringReader
Provides a character stream where the data is
obtained from a String.

FileReader (subclass of InputStreamReader)


A convenience class to provide a character
based stream from file.
Alternatively, open the file using a
FileInputStream and then pass that stream to an
InputStreamReader instance.
Character-Oriented Writer Classes

Writer

PipedWriter CharArrayWriter FileWriter StringWriter

BufferedWriter OutputStreamWriter PrintWriter

FileWriter
Writer Methods
There are 5 main write methods:
void write(int c) :Writes a single character.
void write(char[] buffer) :Writes an array of chars.
void write(char[] buffer, int offset, int length) :
Writes a portion of an array of characters starting at
offset length indicates characters to write.
void write(String aString) :Writes aString to stream.
void write(String aString, int offset, int length)
Writes a portion of a String to the stream
starts at offset , length indicates characters to
write.
Creating a Writer Object
Writer is abstract. Programmers
instantiate one of its subclasses.
BufferedWriter :Writes text to the character
stream
Provides buffering to provide efficient writing of
characters, arrays and lines
CharArrayWriter :Similar to
ByteArrayOutputStream
Characters written to the stream are stored in a
buffer.
The buffer can be retrieved by calling
toCharArray() or toString()
FilterWriter
An abstract class for writing filtered character
Creating a Writer
Object
OutputStreamWriter
This class acts as a bridge from character streams to byte
streams
Characters written to the OutputStreamWriter are
translated to bytes (based on the encoding) and written to
the underlying OuputStream.
PipedWriter
Similar to PipedOutputStream
Connects to an Instance of PipedReader
StringWriter
Characters written to this stream are collected in a
StringBuffer.
The StringBuffer can be used to construct a String.
Creating a Writer
Object
PrintWriter
Provides print() and println() methods for standard output
both print() and println() are overloaded to take a variety of
types
System.out and System.err are PrintWriters

FileWriter (subclass of OutputStreamWriter)


A convenience class for writing characters to file
FileWriters assume that the default character encoding is
acceptable
Input Stream Vs Reader Class
Input Stream Class Reader Stream Class
Input Streams are used to Reader class reads
read bytes from stream. character streams
Useful for binary data Reader class is used to
such as images,video,and read character data.
serialized objects.
Input stream is byte A reader is Character
oriented Oriented.
Output Stream Vs Writer Class
Output Stream Writer Class
Output Streams are Writer classes are used
used to write bytes to to write character
stream. streams.
An output stream is byte An writer is character
oriented oriented.
OutputStream classes Writer class is used to
are used to write 8 bit write 16 bit Unicode
bytes. character stream
File Streams
• A file class is defined in package java.io.
• A file can be created using File class.
• Example :
File f;
f= new File(String Filename);
• The File class contains methods to perform
various file operations.
• Creating a file, Opening a file, Closing a file,
Deleting a file, Getting name of file , etc.
File Class Methods
String getName(): Returns the name of file.
String getParent(): Returns name of parent directory.
boolean exists(): Returns true if file exists.
String getPath():Gets the path of file.
String list(): List the files in directory
boolean createNewFile(): creates new File.
boolean delete(): deletes the file or directory
FileInputStream and
FileOutputStream
• The File class explains only the file System. Java
provides two special stream classes to read and write
into file.
• These two classes operate onto files in native file
system.
• These two classes are subclass of InputStream and
outputstream classes respectively.

Serialization
• Serialization means storing an object in storage
medium (file/ memory buffer) or to transmit it over a
network in binary form.

You might also like