0% found this document useful (0 votes)
24 views54 pages

8-Introduction and Implementation of Byte Stream, Character Stream, Buffered Strea

The document provides an overview of Java I/O streams, specifically focusing on byte streams and their classes, including InputStream and OutputStream. It explains the functionality of buffered streams, predefined streams, and the use of FileInputStream and FileOutputStream for reading and writing data. Additionally, it covers DataInputStream and DataOutputStream for handling primitive data types and ObjectInputStream and ObjectOutputStream for object serialization and deserialization.

Uploaded by

Loki Sundhar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views54 pages

8-Introduction and Implementation of Byte Stream, Character Stream, Buffered Strea

The document provides an overview of Java I/O streams, specifically focusing on byte streams and their classes, including InputStream and OutputStream. It explains the functionality of buffered streams, predefined streams, and the use of FileInputStream and FileOutputStream for reading and writing data. Additionally, it covers DataInputStream and DataOutputStream for handling primitive data types and ObjectInputStream and ObjectOutputStream for object serialization and deserialization.

Uploaded by

Loki Sundhar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Java I/O Streams

Byte Streams
Byte Streams
• Depending upon the data a stream holds, it can be classified into:
• Byte Stream
• Character Stream
• Byte stream is used to read and write a single byte (8 bits) of data.
• All byte stream classes are derived from base abstract classes called
• InputStream and
• OutputStream.
• Byte streams are used, for example, when reading or writing binary
data.
Java.io➔Byte Stream Classes
• classes: InputStream and
OutputStream.
• Each abstract class has several
concrete subclasses that handle
the differences among various
devices, such as disk files,
network connections, and even
memory buffers.
• the most important are read()
and write(), which, respectively,
read and write bytes of data
I/O Stream classes
Byte Stream
InputStream class
• The Java InputStream class, java.io.InputStream, represents an ordered stream of bytes.
• You can read data from a Java InputStream as an ordered sequence of bytes.
• This is useful when reading data from a file, or received over the network.
• The InputStream subclasses are:
• ByteArrayInputStream
• FileInputStream
• PipedInputStream
• BufferedInputStream
• FilterInputStream
• PushbackInputStream
• DataInputStream
• ObjectInputStream
• SequenceInputStream
Here methods throws
IOException,
IndexOutOfBounds ,
InputStream Methods NullpointerException
OutputStream class
• The Java OutputStream class, java.io.OutputStream, is the base class
of all output streams
• Some of the well-known subclasses of the Java OutputStream class:
• ByteArrayOutputStream
• FileOutputStream
• PipedOutputStream
• BufferedOutputStream
• FilterOutputStream
• DataOutputStream
• PrintStream
• ObjectOutputStream
OutputStream methods Here methods throws
IOException,
Buffered Byte Streams
• For the byte-oriented streams, a buffered stream extends a filtered
stream class by attaching a memory buffer to the I/O stream.
• This buffer allows Java to do I/O operations on more than a byte at a
time, thereby improving performance.
• Because the buffer is available, skipping, marking, and resetting of
the stream become possible.
• The buffered byte stream classes are BufferedInputStream and
BufferedOutputStream.
BufferedInputStream
• Buffering I/O is a very common performance optimization.
• Java’s BufferedInputStream class allows you to “wrap” any InputStream into a buffered
stream to improve performance
• The important points about BufferedInputStream are:
• When the bytes from the stream are skipped or read, the internal buffer automatically refilled
from the contained input stream, many bytes at a time.
• When a BufferedInputStream is created, an internal buffer array is created.
• BufferedInputStream has two constructors:
• BufferedInputStream(InputStream inputStream) 1.Default buffer size
2. Size of bufsize
• BufferedInputStream(InputStream inputStream, int bufSize) buffer
• Internal buffer size is 8192 characters
Same as that of InputStream as it
BufferedInputStream methods inherits all base class methods
BufferedOutputStream
• A BufferedOutputStream is similar to any OutputStream with the
exception of an added flush( ) method that is used to ensure that
data buffers are written to the stream being buffered.
• BufferedOutputStream(OutputStream outputStream)
• BufferedOutputStream(OutputStream outputStream, int bufSize)
The Predefined Streams
• All Java programs automatically import the java.lang package.
• This package defines a class called System, which encapsulates
several aspects of the runtime environment.
• For example, one can obtain the current time and the settings of various
properties associated with the system.
• System also contains three predefined stream reference variables: in,
out, and err.
• These fields are declared as public, static, and final within System.
• This means that they can be used by any other part of your program and
without reference to a specific System object
The Predefined Streams
• System.out ➔standard output stream.
• By default, this is the console.
• System.in ➔standard input, which is the keyboard by
default.
• System.err ➔standard error stream, which also is the
console by default.
• However, these streams may be redirected to any compatible
I/O device.
• System.in is an object of type InputStream;
• System.out and System.err are objects of type
PrintStream
Create a Java File Object
• To create an object of File, import the java.io.File package first.
• Once we import the package, create objects of file.

• The object can be used to work with files and directories.

https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/File.html
Basic File Functions
FileInputStream class
• Java FileInputStream class obtains input bytes from a file.
• Used for reading byte-oriented data (streams of raw bytes)
such as image data, audio, video etc.
throws
• For reading streams of characters, it is recommended to FileNotFoundException
use FileReader class.
• public class FileInputStream extends InputStream

https://docs.oracle.com/en/java/javase/11/docs/api/java.base/
java/io/FileInputStream.html
FileInputStream methods
FileOutputStream
• A file output stream is an output stream for writing data to a File or to
a FileDescriptor.
• Whether or not a file is available or may be created depends upon
the underlying platform
• FileOutputStream is meant for writing streams of raw bytes such as
image data.
• For writing streams of characters, consider using FileWriter.
FileOutputStream Constructors

https://docs.oracle.com/en/java/javase/11/docs/api/java.base/
java/io/FileOutputStream.html
FileOutputStream methods
Reading and writing contents of a file
• Java FileOutputStream Class➔An output stream used for writing data
to a file.
• public class FileOutputStream extends OutputStream
• Used to write primitive values into a file
• Can write byte-oriented as well as character-oriented data through
FileOutputStream class.
• Java FileInputStream class➔ obtains input bytes from a file.
• public class FileInputStream extends InputStream
• It is used for reading byte-oriented data (streams of raw bytes) such as image
data, audio, video etc.
No file names
out.txt exists, it
creates new one
No file names
out.txt exists, it
creates new one
Appending contents to end of the File
FileInput and OutputStream using BufferedStream
DataInputStream and DataOutputStream
Filtered Byte Streams
• Filtered streams are simply wrappers around underlying input or output
streams that transparently provide some extended level of functionality.
• Typical extensions are buffering, character translation, and raw data translation
• These streams are typically accessed by methods that are expecting a
generic stream, which is a superclass of the filtered streams.
• The filtered byte streams are FilterInputStream and FilterOutputStream
• FilterOutputStream(OutputStream os)
• FilterInputStream(InputStream is)
• The methods provided in these classes are identical to those in
InputStream and OutputStream
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/FilterInputStream.html
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/FilterOutputStream.html
DataOutputStream and DataInputStream
• Enable you to write or read primitive data to or from a stream.
• They implement the DataOutput and DataInput interfaces,
• These interfaces define methods that convert primitive values to or from a
sequence of bytes.
• These streams make it easy to store binary data, such as integers or
floating-point values, in a file.
DataInputStream
• public class DataInputStream extends FilterInputStream implements
DataInput
• A data input stream lets an application read primitive Java data
types from an underlying input stream in a machine-independent
way.
• An application uses a data output stream to write data that can later
be read by a data input stream.
https://docs.oracle.com/en/java/javase/11/docs/api/java.bas
DataInputStream e/java/io/DataInputStream.html

Methods
• public final int read​(byte[] b) throws IOException
• Reads some number of bytes from the contained input stream
and stores them into the buffer array b.
• The number of bytes actually read is returned as an integer
• public final int read​(byte[] b, int off, int len) throws
IOException
• Reads up to len bytes of data from the contained input stream
into an array of bytes b starting from the off.
• The number of bytes actually read is returned as an integer.
• Throws:
• NullPointerException - If b is null.
• IndexOutOfBoundsException - If off is negative, len is negative, or len is greater
than b.length - off
• IOException - if the first byte cannot be read for any reason other than end of
file, the stream has been closed and the underlying input stream does not
support reading after close, or another I/O error occurs.
DataInputStream Methods
• public final void readFully​(byte[] b) throws IOException
• used to read bytes equal to the length of byte array b from an input stream and store them into
the byte array b
• public final void readFully​(byte[] b, int off, int len) throws IOException
• Throws:
• NullPointerException - if b is null.
• EOFException - if this input stream reaches the end before reading all the bytes.
• IOException - the stream has been closed and the contained input stream does not support reading
after close, or another I/O error occurs.
• IndexOutOfBoundsException - if off is negative, len is negative, or len is greater than b.length - off.

• public final int skipBytes​(int n) throws IOException


• n - the number of bytes to be skipped.
• Returns the actual number of bytes skipped.
DataInputStream Methods
• public final boolean readBoolean() throws IOException or EOF Exception
• Returns the boolean value read.
• public final byte readByte() throws IOException or EOF Exception
• Returns the next byte of this input stream as a signed 8-bit byte.
• public final short readShort() throws IOException or EOF Exception
• Returns the next two bytes of this input stream, interpreted as a signed 16-bit
number.
• public final int readUnsignedShort() throws IOException or EOF Exception
• Returns the next two bytes of this input stream, interpreted as an unsigned 16-bit
integer.
• public final char readChar() throws IOException or EOF Exception
• Returns the next two bytes of this input stream, interpreted as a char.
DataInputStream Methods
• public final int readInt() throws IOException or EOFException:
• Returns the next four bytes of this input stream, interpreted as an int.
• public final long readLong() throws IOException or EOFException:
• Returns: the next eight bytes of this input stream, interpreted as a long.
• public final float readFloat() throws IOException or EOFException:
• Returns the next four bytes of this input stream, interpreted as a float.
• public final double readDouble() throws IOException or EOFException:
• Returns: the next eight bytes of this input stream, interpreted as a double.
• public final String readLine() throws IOException Deprecated use
• Returns the next line of text from this input stream. Bufferedreader
DataInputStream Methods
• public final String readUTF() throws IOException Returns a Unicode
string.
• public static final String readUTF​(DataInput in) throws IOException
• Reads from the stream in a representation of a Unicode character string
encoded in modified UTF-8 format;
• this string of characters is then returned as a String.

• Throws:
• EOFException - if the input stream reaches the end before all the bytes.
• IOException - the stream has been closed and the contained input stream does not support
reading after close, or another I/O error occurs.
• UTFDataFormatException - if the bytes do not represent a valid modified UTF-8 encoding of
a Unicode string.
DataOutputStream
• public class DataOutputStream extends FilterOutputStream impleme
nts DataOutput
• A data output stream lets an application write primitive Java data
types to an output stream in a portable way.
• An application can then use a data input stream to read the data back
in.
DataOutputStream methods
Object InputStream and Object Output Stream

Useful when you want to save


the state of your program to a
persistent storage area, such as a
file.

• Serialization is the
process of writing the
state of an object to a
byte stream.

The rule is that we can write only that object to the streams that support the java.io.Serializable interface.
Serializable Interface
• Only an object that implements the Serializable interface can be
saved and restored by the serialization facilities.
• The Serializable interface defines no members.
• It is simply used to indicate that a class may be serialized.
• If a class is serializable, all of its subclasses are also serializable.
• Variables that are declared as transient are not saved by the
serialization facilities.
• Also, static variables are not saved.
Java ObjectInputStream Class
• The ObjectInputStream class of the java.io package can be used to
read objects that were previously written by ObjectOutputStream.
• Used to read data written by the ObjectOutputStream.
• The ObjectOutputStream converts Java objects into corresponding
streams➔serialization.
• Converted streams can be stored in files or transferred through
networks.
• To read those objects, we will use the ObjectInputStream that will
convert the streams back to corresponding objects.
• Deserialization
ObjectInputStream
• An ObjectInputStream deserializes primitive data and objects
previously written using an ObjectOutputStream.

• Creating ObjectInputStream
Methods of ObjectInputStream

https://docs.oracle.com/en/java/javase/11/docs/api/java.bas
e/java/io/ObjectInputStream.html
ObjectOutputStream
• the ObjectOutputStream encodes Java objects using the class name
and object values.
• And, hence generates corresponding streams.
• Converted streams can be stored in files and can be transferred
among networks.

• The ObjectOutputStream class only writes those objects that implement


the Serializable interface.
• Because objects need to be serialized while writing to the stream.
Create an ObjectOutputStream
• To create an object output stream, we must import the
java.io.ObjectOutputStream package first.

https://docs.oracle.com/en/java/javase/11/docs/api/java.bas
e/java/io/ObjectOutputStream.html
Methods of ObjectOutputStream
The String class and all the
wrapper classes implement the
java. io. Serializable interface by
default.

You might also like