• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Stream » Byte Stream Classes in java
Next →
← Prev

Byte Stream Classes in java

By Dinesh Thakur

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
  • Output Stream classes

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.

You’ll also like:

  1. Character Stream Classes in Java
  2. File input Stream and File Output Stream
  3. Write byte array to a file using FileOutputStream | Java Examples
  4. Java Byte Example
  5. Java’s Magic: The Byte Code
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

SQL Tutorials

SQL Tutorials

  • SQL - Home
  • SQL - Select
  • SQL - Create
  • SQL - View
  • SQL - Sub Queries
  • SQL - Update
  • SQL - Delete
  • SQL - Order By
  • SQL - Select Distinct
  • SQL - Group By
  • SQL - Where Clause
  • SQL - Select Into
  • SQL - Insert Into
  • SQL - Sequence
  • SQL - Constraints
  • SQL - Alter
  • SQL - Date
  • SQL - Foreign Key
  • SQL - Like Operator
  • SQL - CHECK Constraint
  • SQL - Exists Operator
  • SQL - Drop Table
  • SQL - Alias Syntax
  • SQL - Primary Key
  • SQL - Not Null
  • SQL - Union Operator
  • SQL - Unique Constraint
  • SQL - Between Operator
  • SQL - Having Clause
  • SQL - Isnull() Function
  • SQL - IN Operator
  • SQL - Default Constraint
  • SQL - Minus Operator
  • SQL - Intersect Operator
  • SQL - Triggers
  • SQL - Cursors

Advanced SQL

  • SQL - Joins
  • SQL - Index
  • SQL - Self Join
  • SQL - Outer Join
  • SQL - Join Types
  • SQL - Cross Join
  • SQL - Left Outer Join
  • SQL - Right Join
  • SQL - Drop Index
  • SQL - Inner Join
  • SQL - Datediff() Function
  • SQL - NVL Function
  • SQL - Decode Function
  • SQL - Datepart() Function
  • SQL - Count Function
  • SQL - Getdate() Function
  • SQL - Cast() Function
  • SQL - Round() Function

Other Links

  • SQL - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW