Byte stream classes are used to perform reading and writing of 8-bit bytes. Streams being unidirectional in nature can transfer bytes in one direction only, that is, either reading data from the source into a program or writing data from a program to the destination. Therefore, Java further divides byte stream classes into two classes, namely, InputStream class and OutputStrearn class. The subclasses of InputStrearn class contain methods to support input and the subclasses of OutputStrearn class contain output related methods.
We’ll be covering the following topics in this tutorial:
Input Stream Classes
Java’s input stream classes are used to read 8-bit bytes from the stream. The InputStrearn class is the superclass for all byte-oriented input stream classes. All the methods of this class throw an IOException. Being an abstract class, the InputStrearn class cannot be instantiated hence, its subclasses are used. Some of these are listed in Table
Table Input Stream Classes
Class | Description |
BufferedInputStream | contains methods to read bytes from the buffer (memory area) |
ByteArrayInputStream | contains methods to read bytes from a byte array |
DataInputStream | contains methods to read Java primitive data types |
FileInputStream | contains methods to read bytes from a file |
FilterInputStream | contains methods to read bytes from other input streams which it uses as its basic source of data |
ObjectInputStream | contains methods to read objects |
PipedInputStream | contains methods to read from a piped output stream. A piped input stream must be connected to a piped output stream |
SequenceInputStream | contains methods to concatenate multiple input streams and then read from the combined stream |
The Input Stream class defines various methods to perform reading operations on data of an input stream. Some of these methods along with their description are listed in Table
Table InputStream Class Methods
Method | Description |
int read() | returns the integral representation of the next available byte of input. It returns -1 when end of file is encountered |
int read (byte buffer []) | attempts to read buffer. length bytes into the buffer and returns the total number of bytes successfully read. It returns -1 when end of file is encountered |
int read (byte buffer [], int loc, int nBytes) | attempts to read ‘nBytes’ bytes into the buffer starting at buffer [loc] and returns the total number of bytes successfully read. It returns -1 when end of file is encountered |
int available () | returns the number of bytes of the input available for reading |
Void mark(int nBytes) | marks the current position in the input stream until ‘nBytes’ bytes are read |
void reset () | Resets the input pointer to the previously set mark |
long skip (long nBytes) | skips ‘nBytes’ bytes of the input stream and returns the number of actually skippedbyte |
void close () | closes the input source. If an attempt is made to read even after closing the stream then it generates IOException |
Using ByteArrayinputStream Class
The ByteArrayinputStream class opens an input stream to read bytes from a byte array. It contains an internal buffer that holds bytes that are read from the stream. It should be noted that closing the stream does not have any consequences. That is, methods of this class can be invoked even after closing the stream without generating any IOException.
The ByteArrayinputstream object can be created using one of the following constructors.
ByteArrayinputStream(byte[] buffer) //first
ByteArrayinputStream(byte[] buffer, int loc, int nBytes)
//second
The first constructor creates a ByteArrayinputStream which uses a byte array buffer as its input source. The second constructor creates a ByteArrayinputStream which uses a subset of byte array buffer as its input source. The reading begins from the index specified by loc and continues until nBytes are read.
// A Program to demonstrate the use of ByteArrayInputStream class
import java.io.*;
class ByteArrayInputStreamExample
{
public static void main(String args[]) throws IOException
{
byte b[]=”this is my first program”.getBytes();
ByteArrayInputStream inp =new ByteArrayInputStream(b);
int n=inp.available();
System.out.println(“Number of available bytes: “+n);
long s=inp.skip(11); //skipping 11 bytes
System.out.println(“Number of skipped bytes: “+s);
int i;
System.out.print(“String after skipping s bytes: “);
while((i=inp.read()) != -1)
{
System.out.print((char)i);
}
inp.reset(); /*reset the pointer to the beginning of the stream*/
System.out.println(); //new line
int j;
System.out.print(“String in uppercase: “);
while((j=inp.read()) != -1)
{
System.out.print(Character.toUpperCase((char) j));
}
}
}
The output of the program is
Number of available bytes: 24
Number of skipped bytes: 11
String after skipping s bytes: first program
String in uppercase: THIS IS MY FIRST PROGRAM
In this example, the getBytes () method is used to convert string into bytes. The use of available () and skip () methods is demonstrated here. Once the entire stream is read, reset () method is invoked to set the pointer at the start of the stream.
Output Stream classes
Java’s output stream classes are used to write 8-bit bytes to a stream. The OutputStream class is the superclass for all byte-oriented output stream classes. All the methods of this class throw an IOException. Being an abstract class, the OutputStream class cannot be instantiated hence, its subclasses are used. Some of these are listed in Table
Table Output Stream Classes
Class | Description |
BufferedOutputStream | Contains methods to write bytes into the buffer |
ByteArrayOutputStream | Contains methods to write bytes into a byte array |
DataOutputStream | Contains methods to write Java primitive data types |
FileOutputStream | Contains methods to write bytes to a file |
FilterOutputStream | Contains methods to write to other output streams |
ObjectOutputStream | Contains methods to write objects |
PipedOutputStream | Contains methods to write to a piped output stream |
PrintStream | Contains methods to print Java primitive data types |
The OutputStream class defines methods to perform writing operations. These methods are discussed in Table
TableOutputStream Class Methods
.Method | Description |
void write (int i) | writes a single byte to the output stream |
void write (byte buffer [] ) | writes an array of bytes to the output stream |
Void write(bytes buffer[],int loc, int nBytes) | writes ‘nBytes’ bytes to the output stream from the buffer b starting at buffer [loc] |
void flush () | Flushes the output stream and writes the waiting buffered output bytes |
void close () | closes the output stream. If an attempt is made to write even after closing the stream then it generates IOException |
Using ByteArrayOutputStream Class
TheByteArrayOutputStreamclass,anoutputcounterpartoftheByteArrayinputStream, writes streams of bytes to the buffer. Similar to ByteArrayinputStream, closing this stream has no effect. That is, methods of this class can be invoked even after closing the stream without generating any IOException.
The ByteArrayOutputStream object can be created using one of the following constructors.
ByteArrayOutputStream () I /first
ByteArrayOutputStream(int nBytes) //second
The first constructor creates a buffer of 32 bytes. The second constructor creates a buffer of size equal to nBytes. The size of the buffer increases as bytes are written to it.
// A Program to demonstrate the use of ByteArrayOutputStream class
import java.io.*;
class ByteArrayOutputStreamExample
{
public static void main(String args[]) throws IOException
{
ByteArrayOutputStream out=new ByteArrayOutputStream();
byte b[]=”Today is a bright sunny day”.getBytes();
out.write(b);
System.out.println(out.toString() ); /*converting byte array to String*/
out.close(); //closing the stream
}
}
The output of the program is
Today is a bright sunny day
In this example, the getBytes () method is used to convert string into bytes. Once the entire stream is written, the to String ( ) method is invoked to convert the contents (bytes) of the buffer into a string.