Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Stream classes in Java

Today we are going to learn about “Stream classes in Java”. In this article, we are going to learn about several classes of stream for handling files in java.

Introduction:

A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination. InputStream and OutputStream are the basic stream classes in Java.

All the other streams just add capabilities to the basics, like the ability to read a whole chunk of data at once for performance reasons (BufferedInputStream) or convert from one kind of character set to Java's native unicode (Reader), or say where the data is coming from (FileInputStream, SocketInputStream and ByteArrayInputStream, etc.)

Why we need Stream Classes?

To perform read and write operation on binary files we need a mechanism to read that binary data on file/to write binary data (i.e. in the form of byte). These classes are capable to read and write one byte on binary files. That’s why we use Stream Classes.

Stream Classes

Figure 1: Stream Classes

Stream Classes:

Hierarchy of classes for Input and Output streams.

Here Object is the sequence of character i.e. Stream.

1. FileInputStream and FileOutputStream Classes:

FileInputStream Class:

A FileInputStream is an InputStream to obtain bytes from a file. It is used for reading inputs of raw bytes such as image data. It can read byte oriented data.

Constructor to take file for input:

InputStream f=new FileInputStream(“C:/JavaProg/Demo”);

Here, f is an object of InputStream class and argument of FileInputStream is that path where our file is located.

Methods of FileInputStream:

1. Public void close () throws IOException {}
This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException
2. Protected void finalize () throws IOException {}
This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException.
3. Public int read (int r) throws IOException {}
This method reads the specified byte of data from the InputStream. Returns an int. Returns the next byte of data and -1 will be returned if it's end of file.
4. Public int read (int r) throws IOException {}
This method reads the specified byte of data from the InputStream. Returns an int. Returns the next byte of data and -1 will be returned if it's end of file.
5.

public int available() throws IOException{}

Gives the number of bytes that can be read from this file input stream. Returns an int.

Listing 1: Demo of FileInputStream Class

import java.io.*;

public class fileInputStreamDemo {

   public static void main (String args[]){
   
   try {
      byte bWrite [] = {10, 20,30,40,50};
      OutputStream os = new FileOutputStream("C:/test.txt");
      for(int x=0; x < bWrite.length ; x++){
         os.write( bWrite[x] ); // writes the bytes
      }
      os.close();
     
      InputStream is = new FileInputStream("C:/test.txt");
      int size = is.available();

      for(int i=0; i< size; i++){
         System.out.print((char)is.read() + "  ");
      }
      is.close();
   }catch(IOException e){
      System.out.print("Exception");
   }	
   }
}

Output of the program is:

10 20 30 40 50

A FileOutputStream is used to create a file and write data into it. The stream would create a file, if it doesn't already exist, before opening it for output.

Constructors for FileOutputStream Class:

Constructor Description
FileOutputStream(File file) Creates a file output stream to write to the file represented by the specified File object.
FileOutputStream(File file, boolean append) Creates a file output stream to write to the file represented by the specified File object.
FileOutputStream(String name) Creates an output file stream to write to the file with the specified name.
FileOutputStream(String name, boolean append)

Creates an output file stream to write to the file with the specified name.


Methods of FileOutStream:


Constructor Description
void close()  This method closes this file output stream and releases any system resources associated with this stream
protected void finalize() This method cleans up the connection to the file, and ensures that the close method of this file output stream is called when there are no more references to this stream.
FileChannel getChannel() This method returns the unique FileChannel object associated with this file output stream.
FileDescriptor getFD()

This method returns the file descriptor associated with this stream.

void write(byte[] b) This method writes b.length bytes from the specified byte array to this file output stream.
void write(byte[] b, int off, int len) This method writes len bytes from the specified byte array starting at offset off to this file output stream.
void write(int b) This method writes the specified byte to this file output stream.

Example:

Listing 2: Program to demonstrate FileOutputStream Class

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamDemo {
   public static void main(String[] args) throws IOException {
      
      FileOutputStream fos = null;
      FileInputStream fis = null;
      int i=0;
      char c;
      
      try{
         // create new file output stream
         fos=new FileOutputStream("C://test.txt");
         
         // writes byte to the output stream
         fos.write(b, 2, 3);
         
         // flushes the content to the underlying stream
         fos.flush();
         
         // create new file input stream
         fis = new FileInputStream("C://test.txt");
         
         // read till the end of the file
         while ((i=fis.read())!=-1)
         {
            // convert integer to character
            c=(char)i;
            
            // prints
            System.out.print(c);
         }
   
         // if an error occurs
         e.printStackTrace ();
      } finally {
         
         // closes and releases system resources from stream
         if(fos!=null)
            fos.close();
         if(fis!=null)
            fis.close();
      }
   }
}

Output of the Program is:

CDE

2. ByteArrayInputStream and ByteArrayOutputStream Class:

ByteArrayInputStream:

This class contains an internal buffer that contains bytes that may be read from the stream. An internal counter keeps track of the next byte to be supplied by the read method. The methods in this class can be called after the stream has been closed without generating an IOException.

Constructors for ByteArrayInputStream:

Constructor Description
ByteArrayInputStream(byte[] buf)  This creates a ByteArrayInputStream so that it uses buf as its buffer array.
ByteArrayInputStream(byte[] buf, int offset, int length)  This creates ByteArrayInputStream that uses buf as its buffer array.

Methods of ByteArrayInputStream:


Methods Description
int available() This method returns the number of remaining bytes that can be read (or skipped over) from this input stream.
void close() Closing a ByteArrayInputStream has no effect.
void mark(int readAheadLimit) This method set the current marked position in the stream.
boolean markSupported() This method tests if this InputStream supports mark/reset.
int read() This method reads the next byte of data from this input stream.
int read(byte[] b, int off, int len) This method reads up to len bytes of data into an array of bytes from this input stream.
void reset() This method resets the buffer to the marked position.
long skip(long n) This method skips n bytes of input from this input stream.

ByteArrayOutputStream:

This class implements an output stream in which the data is written into a byte array. The buffer automatically grows as data is written to it. The methods in this class can be called after the stream has been closed without generating an IOException.

Constructors for ByteArrayInputStream:

Constructor Description
ByteArrayOutputStream() This creates a new byte array output stream.
ByteArrayOutputStream (int size) This creates a new byte array output stream, with a buffer capacity of the specified size, in bytes.

Methods of ByteArrayInputStream:


Methods Description
int size() This method returns the current size of the buffer.
void close() Closing a ByteArrayInputStream has no effect.
void reset() This method resets the count field of this byte array output stream to zero, so that all currently accumulated output in the output stream is discarded.
String toString(String charsetName) This method converts the buffer's contents into a string decoding bytes using the platform's default character set.
byte[] toByteArray() This method creates a newly allocated byte array.
void write(byte[] b, int off, int len) This method writes len bytes from the specified byte array starting at offset off to this byte array output stream.
void write(int b) This method Writes the specified byte to this byte array output stream.
void writeTo(OutputStream out) This method writes the complete contents of this byte array output stream to the specified output stream argument, as if by calling the output stream's write method using out.write(buf, 0, count).

Example:

Listing 3: Program to demonstrate ByteArrayInputStream and ByteArrayOutputStream:

import java.io.*;

public class ByteStreamTest {

   public static void main(String args[])throws IOException {

      ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12);

      while( bOutput.size()!= 10 ) {
         // Gets the inputs from the user
         bOutput.write(System.in.read()); 
      }

      byte b [] = bOutput.toByteArray();
      System.out.println("Print the content");
      for(int x= 0 ; x < b.length; x++) {
         // printing the characters
         System.out.print((char)b[x]  + "   "); 
      }
      System.out.println("   ");

      int c;

      ByteArrayInputStream bInput = new ByteArrayInputStream(b);

      System.out.println("Converting characters to Upper case " );
      for(int y = 0 ; y < 1; y++ ) {
         while(( c= bInput.read())!= -1) {
            System.out.println(Character.toUpperCase((char)c));
         }
         bInput.reset(); 
      }
   }
}

Output of the Program is:

asdfghjkly
Print the content
a s d f g h j k l y
Converting characters to Upper case
A
S
D
F
G
H
J
K
L
Y

Conclusion

FileInput and FileOutput streams are the streams that are used to read/write byte of data to a file. While ByteInputArray and ByteOutputArray read/write bytes of data at a time because it deals with array of byte and works faster than FileInput and FileOutput Stream.



I am a software developer from India with hands on experience on java, html for over 5 years.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login