Byte Streams in Java

Byte Streams in Java with Examples

In this article, I am going to discuss Byte Streams in Java with Examples. Please read our previous article where we discussed Java IO Stream in detail. As part of this article, you will understand the need and use of the following classes with examples which come under the Java Byte Steams.

  1. FileInputStream Class in Java
  2. FileOutputStream Class in Java
  3. ByteArrayInputStream Class in Java
  4. ByteArrayOutputStream Class in Java
  5. DataInputStream Class in Java
  6. DataOutputStream Class in Java
  7. BufferedInputStream Class
  8. BufferedOutputStream Class in Java
  9. ObjectInputStream Class in Java
  10. ObjectOutputStream Class in Java
  11. PrintStream Class in Java

Note: The stream which reads and writes the data in the form of bytes is called Binary Streams.

FileInputStream Class in Java

This stream is used to read the content of the specified file byte by byte. Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video, etc. It extends the InputStream abstract class.

Creating FileInputStream object: FileInputStream fis = new FileInputStream(“filename”);

Sample Program to understand FileInputStream class
import java.io.FileInputStream;
public class FileInputStreamDemo
{
  public static void main (String[]args)
  {
    try
    {
        FileInputStream fis = new FileInputStream ("input.txt");

        System.out.println ("Data in the file: ");

        // Reads the first byte
        int ch = fis.read ();

        while (ch != -1)
     {
         System.out.print ((char) ch);

         // Reads next byte from the file
         ch = fis.read ();
     }
        fis.close ();
    }
    catch (Exception e)
    {
        e.getStackTrace ();
    }
  }
}

Output: Suppose we have a file named input.txt

Program to understand FileInputStream class

Note: While reading the data from a file if the specified file is not available then it will throw a run time exception called FileNotFoundException. fis.read() method returns -1 if there are no bytes to read which is nothing but end position of the file.

Methods of FileInputStream Class
  1. int available(): It is used to return the estimated number of bytes that can be read from the input stream.
  2. int read(): It is used to read the byte of data from the input stream.
  3. int read(byte[] b): It is used to read up to b.length bytes of data from the input stream.
  4. int read(byte[] b, int off, int len): It is used to read up to len bytes of data from the input stream.
  5. long skip(long x): It is used to skip over and discard x bytes of data from the input screen.
  6. protected void finalize(): It is used to ensure that the close method is called when there is no more reference to the file input stream.
  7. void close(): It is used to closes the stream.
FileOutputStream Class in Java

This byte stream is used to write the content on to a file byte by byte. It extends the OutputStream abstract class. If you have to write primitive values into a file, use the FileOutputStream class.

Creating FileOutputStream object: Syntax1: FileOutputStream fos = new FileOutputStream(“filename”);

This syntax will create the file if the specified file is not available and write the content otherwise if the file is available then it will overwrite the old content with new content.

Syntax2: FileOutputstream fos = new FileOutputStream(“filename”, true);

This syntax will create the file if the specified file is not available and write the content otherwise if the file is available then it will append old content with new content.

Sample Program to understand FileOutputStream class
import java.io.*;
public class FileOutputStreamDemo
{
    public static void main (String[]args) throws IOException
    {
        FileOutputStream fos = new FileOutputStream ("output.txt", true);
        DataInputStream dis = new DataInputStream (System.in);
        char ch;
        System.out.println ("Enter chars and press # to save");
        ch = (char) dis.read ();
        while (ch != '#')
        {
    	    fos.write (ch);
         ch = (char) dis.read ();
         // Releasing the resources
         fos.close ();
         dis.close ();
        }
    }
}

Output

Program to understand FileOutputStream class

output.txt: HI

Note: While writing data on to a file if the specified file is not available then it won’t throw any run time exception saying FileNotFoundException instead of this it will create the file with the specified name. But it will throw FileNotFoundException if the specified location is not available.

Methods of FileOutputStream Class
  1. protected void finalize(): It is used to clean up the connection with the file output stream.
  2. void write(byte[] ary): It is used to write ary.length bytes from the byte array to the file output stream.
  3. void write(byte[] ary, int off, int len): It is used to write len bytes from the byte array starting at offset off to the file output stream.
  4. void write(int b): It is used to write the specified byte to the file output stream.
  5. void close(): It is used to closes the file output stream.
Sample Program to copy the content of one file into another file
import java.io.*;
public class FileCopyDemo
{
    public static void main (String[]args) throws IOException
    {
        FileInputStream fis = new FileInputStream("input.txt");
     FileOutputStream fos = new FileOutputStream("output.txt");
     int ch;
     ch = fis.read();
     while(ch!= -1) {
      fos.write(ch);
      ch = fis.read();
     }
     fis.close();
     fos.close();
     System.out.println("\nFile Copied Successfully");
    }
}

Output: File Copied Successfully

input.txt

Byte Streams in Java

output.txt

Byte Streams in Java

ByteArrayInputStream Class in Java

ByteArrayInputStream is a byte stream class which is used to read the bytes of byte array byte by byte. It extends the InputStream abstract class. In ByteArrayInputStream, the input stream is created using the array of bytes. It includes an internal array to store data of that particular byte array.

Creating ByteArrayInputStream Object: ByteArrayInputStream bais = new ByteArrayInputStream(byte[]);

Sample Program to understand ByteArrayInputStream class in Java
import java.io.*;
public class ByteArrayInputStreamDemo
{
 public static void main(String[] args) {
  String str = "Hello World";
  byte arrb[] = str.getBytes();
  ByteArrayInputStream bais = new ByteArrayInputStream(arrb);
  int ch;
  ch = bais.read();
  while (ch != -1) {
   System.out.print((char) ch);
   ch = bais.read();
  }
 }
}

Output: Hello World

Note: Here read() method returns -1 if there are no bytes to read which means it reaches to end position.

Methods of ByteArrayInputStream Class
  1. int read(): Reads the single byte from the array present in the input stream.
  2. int read (byte[] array): Reads bytes from the input stream and stores in the specified array.
  3. int read(byte[] array, int start, int length): Reads the number of bytes equal to length from the stream and stores in the specified array starting from the position start.
  4. int available(): To get the number of available bytes in the input stream.
  5. long skip(long x): It is used to skip the x bytes of input from the input stream.
  6. void close() : It is used for closing a ByteArrayInputStream.
  7. void mark(): It is used to set the currently marked position in the stream.
ByteArrayOutputStream Class in Java

The ByteArrayOutputStream class of the java.io package can be used to write an array of output data (in bytes). It extends the OutputStream abstract class. ByteArrayOutputStream maintains an internal array of bytes to store the data.

Creating ByteArrayOutputStream Object: ByteArrayOutputStream out = new ByteArrayOutputStream();

Sample Program to understand ByteArrayOutputStream Class in Java
import java.io.*;
public class ByteArrayOutputStreamDemo
{
 public static void main(String[] args) {
  String data = "Hello World";
     try {
         // Creates an output stream
         ByteArrayOutputStream out = new ByteArrayOutputStream();
         byte[] array = data.getBytes();

         // Writes data to the output stream
         out.write(array);

         // Retrieves data from the output stream in string format
         String streamData = out.toString();
         System.out.println("Output stream: " + streamData);

         out.close();
     }
     catch(Exception e) {
         e.getStackTrace();
     }
 }
}

Output: Output stream: Hello World

Methods of ByteArrayOutputStream Class
  1. void write(int b): Writes the specified byte to the output stream.
  2. void write(byte[] array): Writes the bytes from the specified array to the output stream.
  3. void write(byte[] arr, int start, int length): Writes the number of bytes equal to length to the output stream from an array starting from the position start.
  4. void writeTo(OutputStream out): It is used for writing the complete content of a byte array output stream to the specified output stream.
  5. String toString(): It is used for converting the content into a string decoding bytes using a platform default character set.
  6. byte toByteArray(): returns the array present inside the output stream.
  7. void close(): It is used to close the ByteArrayOutputStream.
  8. int size(): It is used to returns the current size of a buffer.
DataInputStream Class in Java

DataInputStream is a byte stream class which is used to perform reading operation from any input device like keyboard, file, etc. Java DataInputStream class allows an application to read primitive data from the input stream in a machine-independent way.

Creating DataInputStream Object: DataInputStream dis = new DataInputStream(resource);

Sample Program to understand DataInputStream class
import java.io.*;
public class DataInputStreamDemo
{
 public static void main(String[] args) throws IOException {
  DataInputStream dis = new DataInputStream(System.in);
  System.out.println("Enter any string");
  String str = dis.readLine(); //parsing
  System.out.println("str="+str);
  System.out.println("Enter any Integer");
  int i= Integer.parseInt(dis.readLine()); //parsing
  System.out.println("i="+i);
  System.out.println("Enter any Double");
  double d = Double.parseDouble(dis.readLine());
  System.out.println("d="+d);
 }
}

Output

Program to understand DataInputStream class in Java

DataOutputStream Class in Java

Java DataOutputStream class allows an application to write primitive Java data types to the output stream in a machine-independent way. Java application generally uses the data output stream to write data that can later be read by a data input stream.

Creating DataOutputStream Object:  DataOutputStream data = new DataOutputStream(resource);

Sample Program to understand DataOutputStream class in Java
import java.io.*;
public class DataOutputStreamDemo
{
 public static void main(String[] args) throws IOException {  
        FileOutputStream file = new FileOutputStream("input.txt");  
        DataOutputStream data = new DataOutputStream(file);  
        data.writeInt(65);  
        data.flush();  
        data.close();  
        System.out.println("Succcess...");  
    } 
}

Output: Succcess…
input.txt
A

BufferedInputStream Class in Java

The BufferedInputStream class of the java.io package is used with other input streams to read the data (in bytes) more efficiently. It extends the InputStream abstract class.

The important points about BufferedInputStream are:
  1. 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.
  2. When a BufferedInputStream is created, an internal buffer array is created.

Creating BufferedInputStream Object:  BufferedInputStream bin=new BufferedInputStream(resource);

Sample Program to understand BufferedInputStream class
import java.io.*;
public class BufferedInputStreamDemo
{
    public static void main (String[]args)
    {
        try
        {
            // Creates a FileInputStream
            FileInputStream file = new FileInputStream ("input.txt");

            // Creates a BufferedInputStream
            BufferedInputStream input = new BufferedInputStream (file);

            // Reads first byte from file
            int i = input.read ();

            while (i != -1)
         {
             System.out.print ((char) i);

             // Reads next byte from the file
             i = input.read ();
         }
            input.close ();
        }
        catch (Exception e)
        {
            e.getStackTrace ();
        }
    }
}

Output: Hello World

BufferedOutputStream Class in Java

Java BufferedOutputStream class is used for buffering an output stream. It internally uses a buffer to store data. It adds more efficiency than to write data directly into a stream. So, it makes the performance fast. For adding the buffer in an OutputStream, use the BufferedOutputStream class. It extends the OutputStream abstract class.

Creating BufferedOutputStream: BufferedOutputStream bout = new BufferedOutputStream(resource);

Sample Program to understand BufferedInputStream class
import java.io.*;
public class BufferedInputStreamDemo
{
    public static void main (String[]args) throws Exception 
    {
        	FileOutputStream fout = new FileOutputStream("output.txt");
  BufferedOutputStream bout = new BufferedOutputStream(fout);
  String s = "Welcome to Java Programming Language.";
  byte b[] = s.getBytes();
  bout.write(b);
  bout.flush();
  bout.close();
  fout.close();
  System.out.println("success");
    }
}

Output: success
output.txt
Welcome to Java Programming Language.

ObjectInputStream Class in Java

The ObjectInputstream is mainly used to read data written by the ObjectOutputstream. Basically, the ObjectOutputstream converts Java objects into corresponding streams. This is known as serialization. Those converted streams can be stored in files or transferred through networks. Now, if we need to read those objects, we will use the ObjectInputstream that will convert the streams back to corresponding objects. This is known as deserialization.

Creating ObjectInputStream Object: ObjectInputStream object = new ObjectInputStream(resource);

ObjectOutputStream Class in Java

Basically, the ObjectOutputStream encodes Java objects using the class name and object values. And, hence generates corresponding streams. This process is known as serialization. Those converted streams can be stored in files and can be transferred among networks.

Creating ObjectOutputstream Object: ObjectOutputStream object = new ObjectOutputStream(resource);

Note: The ObjectOutputStream only writes those objects that implement the Serializable interface. This is because objects need to be serialized while writing to the stream.

Sample Program to demonstrate ObjectInputStream and ObjectOutputStream Class
import java.io.*;
public class ObjectInputOutputStreamDemo 
{
    public static void main (String[]args)
    {
        int data1 = 5;
        String data2 = "Java is a programming language";
        try {
            FileOutputStream file = new FileOutputStream("file.txt");
            ObjectOutputStream output = new ObjectOutputStream(file);

            // Writing to the file using ObjectOutputStream
            output.writeInt(data1);
            output.writeObject(data2);

            FileInputStream fileStream = new FileInputStream("file.txt");

            // Creating an object input stream
            ObjectInputStream objStream = new ObjectInputStream(fileStream);

            //Using the readInt() method
            System.out.println("Integer data :" + objStream.readInt());
            // Using the readObject() method
            System.out.println("String data: " + objStream.readObject());
            output.close();
            objStream.close();
        }
        catch (Exception e) {
            e.getStackTrace();
        }
    }
}

Output:
Integer data :5
String data: Java is a programming language

PrintStream Class in Java

The PrintStream class of the java.io package can be used to write output data in commonly readable form (text) instead of bytes. It extends the abstract class OutputStream. Unlike other output streams, the PrintStream converts the primitive data (integer, character) into the text format instead of bytes. It then writes that formatted data to the output stream.

Note: The PrintStream class automatically flushes the data so there is no need to call the flush() method. Moreover, its methods don’t throw IOException.

Creating PrintStream Object:

We can create a PrintStream Class by following two ways:

Using other output streams
// Creates a FileOutputStream
FileOutputStream file = new FileOutputStream(String file);
// Creates a PrintStream
PrintStream output = new PrintStream(file, autoFlush);

Using filename
// Creates a PrintStream
PrintStream output = new PrintStream(String file, boolean autoFlush);

Sample Program to understand PrintStream class in Java:
import java.io.*;
public class PrintStreamDemo
{
    public static void main(String args[])throws Exception
    {    
        FileOutputStream fout=new FileOutputStream("output.txt");    
        PrintStream pout=new PrintStream(fout);    
        pout.println(2020);    
        pout.println("Hello Java");    
        pout.println("Welcome to Java");    
        pout.close();    
        fout.close();    
        System.out.println("Success?");    
    }
}

Output: Success?

output.txt

Program to understand PrintStream class in Java

Methods of PrintStream Class
  1. void print(): Prints the specified data to the output stream.
  2. void println(): Prints the data to the output stream along with a new line character at the end.
  3. void printf(): The printf() method can be used to print the formatted string. It includes 2 parameters: formatted string and arguments.
File

This class is used to get the properties of a file like what is the length of the file, what is the path of the file, whether it is a file or not, readable or not, writable or not, existed or not, etc. Using File class we can also delete the file and rename the file. File class is not meant for reading the file or writing the file.

Creation of File: File f = new File(“filename”);

Sample Program
import java.io.*;
public class FileDemo 
{
    public static void main (String args[])
    {
        File f = new File ("file.txt");
        if (f.exists ())
        {
         System.out.println ("Existed:" + f.exists ());
         System.out.println ("File:" + f.isFile ());
         System.out.println ("Directory:" + f.isDirectory ());
         System.out.println ("Readable:" + f.canRead ());
         System.out.println ("Writable:" + f.canWrite ());
         System.out.println ("Path:" + f.getPath ());
         System.out.println ("Absolute Path:" + f.getAbsolutePath ());
         System.out.println ("size:" + f.length () / 1024 + "KB");
        }
        else
        {
         System.out.println ("File is not available");
        }
    }
}

Output

Java Byte Streams

In the next article, I am going to discuss the Java Character Streams in detail with examples. Here, in this article, I try to explain Java Byte Streams with Examples. I hope you enjoy this Java Byte Streams with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this Java Byte Streams with Examples article.

Leave a Reply

Your email address will not be published. Required fields are marked *