Input/Output Stream in java

input/output are the two major processes in any application development.
java follows the stream based input/output.
A stream is a channel through which data will be transmitted.

example:-

Advantages of stream based I/O over Normal I/O:-

Abstraction:- Streams hides the internal complexity of I/O.

Flexibility:- Streams provides a flexibility to be used in the program according to the requirement.

Efficiency:- Streams also performs the additional operations onto the data so stream based I/O always be effective over the normal I/O.
                  Their are two types of streams in java-
1:- Byte Stream:- it follows the 8 bit sequence.
2:- Character Stream:- it follows the 16 bit sequence.
       java.io package provides classes known as Stream classes whose objects are considered as the stream in the java applications.
       InputStream & OutputStream classes:- These are the base classes for all the byte type streams that means all the byte type streams are the child of these classes.
        In these stream classes their are the common methods for the input and output.
                                          -:Methods of InputStream class:- 
                        (1) public int read()
                                       - this method will read the next available byte from the stream. If their is no byte available then this method returns -1.
                        (2) public int read(byte []b)
                                      - this method is used to read all the available bytes from the stream and returns the no. of bytes it read.
                       (3) public int available()
                                     - this method is used to return the no. of bytes available in the stream.
                                        -:Methods of OutputStream class:- 
(1) public void write(int x)
              -this method is used to write the argumented byte in the stream.
      Note- in the argument the value must be within the range of byte i.e. -128 to +127.
      Note- all the integer values that are with in the byte range are treated as byte type in java.
(2) public void write(byte b[])
             -this method is used to write the argumented byte in the stream. 
                                       -:Child classes of the InputStream class:-
                      InputStream
                                    -FileInputStream
                                    -BufferedInputStream
                                    -ByteArrayInputStream
                                    -DataInputStream
                                    -PipedInputStream
                                    -ObjectInputStream
                                    -SequenceInputStream

                                     -:Child classes of OutputStream:-
                      OutputStream
                                    -FileOutputStream
                                    -BufferedOutputStream
                                    -ByteArrayOutputStream
                                    -DataOutputStream
                                    -PipedOutputStream
                                    -ObjectOutputStream
                                    -PrintStream

FileInputStream & FileOutputStream classes:-
                                             -These classes are used to take input from a file and write the output onto the file.
FileOutputStream Constructor:-
                     (1) public FileOutputStream(String file_name)
                                              -This constructor always creates a new file in the file system. If file already exiests then it will override to that file.
                           Example- new FileOutputStream(“abc.txt”);
                                                      //abc.txt file will be created in the current directory.(its an relative path)
                                            new FileOutputStream(“d:\\temp\\abc.txt”);
                                                      //abc.txt will be created in the d:\temp folder.(its an absolute path)
                      (2) public FileOutputStream(File f)
                                               -The object of file class also represents to a file.
File class:- File class is also available in java.io package.

                       (3) public FileOutputStream(String file_name,boolean append)
                                               -This constructor can open a exiesting file if boolean argument be passed as true.
                       (4) public FileOutputStream(File f,boolean append)
                                               -same as the constructor 3.

import java.io.*;
class FileOutputTest
{
                 public static void main(String[] args)
                {
                             try
                            {
                                      FileOutputStream fout=new FileOutputStream(“abc.txt”);
                                      String str[]={“This is line one.”, “this is line two.”, “this is line three.”};
                                      for(int i=0;i<str.length;i++)
                                     {
                                             byte[] b=str[i].getBytes();
                                             fout.write(b);
                                             fout.write(“\n”.getBytes());
                                             //this code will append the byte code of \n with every line.
                                     }
                                     fout.close();
                            }
                            catch(IOException e)
                           {
                                  e.printStackTrace();
                           }
                }
}
output:-
               This is line one.
               This is line two.
               This is line three.

fout.close()close() will close the file that means it will move the file from primary memory to the seconday memory.
Note:- All the input/output operations always throws the IOException.
import java.io.*;
class FileInputTest
{
                 public static void main(String[] args)
                {
                          try
                         {
                                 System.out.println(“File content about to be retrieved.”);
                                 FileInputStream fin=new FileInputStream(“abc.txt”);
                                 while(true)
                                 {
                                         int x=fin.read();
                                         if(x==-1)
                                                break;
                                         System.out.print((char)x);
                                 }
                                 fin.close();
                          }
                          catch(Exception e)
                          {
                                 e.printStackTrace();
                          }
                 }
}

output:-
              This is line one.
              This is line two.
              This is line three.

Note:- The constructor of FileInputStream will open the file and if file does not exiest then FileNotFoundException will be generated.

FileInputStream Constructor:-
                        (1) public FileInputStream(String file_name) throws FileNotFoundException
Note:- the above program of FileInputStream is slow because it repeat the loop upto the no. Of bytes available.

import java.io.*;
class FileInputTest2
{
             public static void main(String[] args)
            {
                      try
                     {
                              System.out.println(“File content about to retrieved.”);
                              FileInputStream fin=new FileInputStream(“abc.txt”);
                              int size=fin.available();
                              byte b[]=new byte[size];
                              //reading the bytes from stream and copied into byte array.
                              fin.read(b);
                              String str=new String(b);
                              System.out.println(str);
                              fin.close();
                    }
                    catch(Exception e)
                    {}
           }
}

output:-
             This is line one.
             This is line two.
             This is line three.

-:CharacterStream:-

Reader & Writer classes- these are base classes for all the character streams.

                   -These are the abstract classes.
                     Methods of Reader class:-
                                             public int read()
                                                           -This method will read the next available character, returns -1 if all the character already been retrieved.
                                             public int read(char []ch)
                                                           -This method will read all the characters from the stream into the argumented character array and returns the no. of characters it retrieved.
                    - no available() exiest in this class.

Methods of Writer class:-

                        (1) public void write(int ch)
                        (2) public void write(char ch[])
                        (3) public void write(String str)


Child classes:-
                  Reader:-
                            -FileReader
                            -BufferedReader
                            -CharArrayReader
                            -InputStreamReader
                 Writer:-
                           -FileWriter
                           -BufferedWriter
                           -CharArrayWriter
                           -OutputStreamWriter

FileReader and FileWriter classes:-
                          -These are the character streams versions of the FileInputStream & FileOutputStream classes.

BufferedReader & BufferedWriter:-
                         -These are high level streams. A high level stream is the stream that always be connected to the low level stream or to the other high level stream.
                          High level streams never be connected directly to any device, file or network. Only low level streams is capable to be connected directly to the file, device or network.
                          High level streams are capable of providing additional functionality over the I/O.
BufferedReader class provides a method readLine() to read the content line by line.
                          public BufferedReader(Reader r)
                                        The argumented CharacterStream will be another high level or low level stream.

To read the content from the file line by line:-


import java.io.*;
class BufferedReaderTest
{
           public static void main(String[] args)
          {
                try
               {
                     FileReader r=new FileReader(“xyz.txt”);
                     BufferedReader br=new BufferedReader(r);
                     while(true)
                     {
                           String str=br.readLine();
                           if(str==null)
                                  break;
                           System.out.println(str);
                     }
                     r.close();
                }
              catch(Exception e)
              {
              }
          }
}

InputSreamReader & OutputStreamWriter:-
                          -InputStreamReader class is also the high level stream.
                          -It is used to convert the ByteStream into the CharacterStream.
                       
                          -OutputStreamWriter class use to convert the CharacterStream into the ByteStream.

                                                             Constructor
                         public InputStreamReader(InputStream in)
                         public OutputStreamWriter(OutputStream out)

-To read the content from FileInputStream line by line.......

                 FileInputStream fin=new FileInputStream("abc.txt");
                 BufferedReader br=new BufferedReader(new InputStreamReader(fin));

-java.lang.System class- This class provides the ready made streams to performs the I/O with the standard devices.
                      System.in-   object of the InputStream to read the data from standard input device (keyboard).
                      System.out-    object of the PrintStream(output stream) which is use to write the data onto the standard output device (console or monitor).
                      System.err-  object of PrintStream which is also connected to the standard output device.

//read the data line by line from the keyboard.
import java.io.*;
class SystemInTest
{
       public static void main(String[] args)
       {
               try
               {
                   BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                   FileOutputStream fout=new FileOutputStream("stud.txt");
                   while(true)
                   {
                          System.out.println("enter the name,rollno,marks and grade");
                          String name=br.readLine();
                          String rollno=br.readLine();
                          String marks=br.readLine();
                          String grade=br.readLine();
                          String str=name+":"+rollno+":"+marks+":"+grade+"\n";
                          fout.write(str.getBytes());
                          System.out.println("do you want to store more records(y/n):");
                          String option=br.readLine();
                          if(option.equalsIgnoreCase("n"))
                                            break;
                   }
               }
               catch(Exception e)
               {
               }
       }
}

Declaration of the Streams in the System class:-
  public final class System
  {
      public static final InputStream in=new <any child of InputStream>(<connecting with keyboard>);
     

      public static final PrintStream out=new PrintStream(<connecting with console>);

      public static final PrintStream err=new PrintStream(<connecting with console>);

      ---------------------------------------------------------------------------------
  }

Note:- Question is how the Stream classes are connected with devices?
            Answer is, There are java classes that contains the code at the JNI(java native interface) to interact with the drivers of the devices and the objects of these java classes are encapsulated in the object of stream.

1.1- java class object created.
1.2- java class object is registered with the stream
2.1- Data from the keyboard entered and retrieved by the keyboard driver.
2.2- Data provided to the java class object.
2.3- Data provided to the stream object.
2.4- from the Stream data obtained in the application.

System class Provides the static methods to change the Streams:-

(1) System.setIn(InputStream in)

(2) System.setOut(PrintStream)

(3) System.setErr(PrintStream)

Through the JNI we can change the final values of 'err'  'in' and 'out'
import java.io.*;
class SystemStreamsChangeTest
{
        public static void main(String[] args)
        {
             try
             {
                 FileInputStream fin=new FileInputStream("file1.txt");
                 PrintStream p1=new PrintStream("file2.txt");
                 PrintStream p2=new PrintStream("fileErr.txt");
                 System.out.println("changing the streams");
                 System.setIn(fin);
                 System.setOut(p1);
                 System.setErr(p2);
                 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                 String str;
                 while((str=br.readLine())!=null)
                 {
                       if(str.length()<10)
                               System.err.println(str);
                       else
                               System.out.println(str);
                 }
                 br.close();
             }
             catch(Exception e){}
        }
}

In the above program the Input Stream is changed to fin i.e. file1.txt and just like that for the output stream and error streams are p1 and p2 i.e. file2.txt and file3.txt, and the content of file1.txt is treated as input source and according to the if condition content is write to the one of the two files (file2.txt and file3.txt).

DataInputStream & DataOutputStream classes:-
         These streams are also the high level streams and provides the methods to load and write the primitive data from the stream.

Constructor:-
          public DataInputStream(InputStream in)
          public DataOutputStream(OutputStream out)

Methods of the DataInputStreams:-
(1) public int readInt()
                -this method is use to read the integer value from the stream.
(2) public float readFloat()
(3) public double readDouble()
(4) public String readLine()
                -it is the deprecated method and its substitute method is the readLine() of BufferedReader
(5) public String readUTF()
                -this method use to read the data in string format in UTF standard.
(6) public void writeInt()
(7) public void writeFloat()
(8) public void writeDouble()
(9) public void writeUTF()

SequenceInputStream:-
                      -This is also the high level stream and it provides the way to make the chain of the InputStreams that means from the multiple InputStreams we can get the data by using the single looped.

Constructor:-
public SequenceInputStream(InputStream in1,InputStream in2)

public SequenceInputStream(Vector v)

Vector:- it is the collection in which we can add the unlimited objects.

import java.io.*;
class SequenceTest
{
     public static void main(String[] args)
     {
          try
          {
              FileInputStream fin1=new FileInputStream("file1.txt");
              FileInputStream fin2=new FileInputStream("file2.txt");
              SequenceInputStream seq=new SequenceInputStream(fin1,fin2);
              BufferedReader br=new BufferedReader(new InputStreamReader(seq));
              String str;
              while((str=br.readLine())!=null)
              {       
                     System.out.println(str);
              }
              br.close();
          }
          catch(Exception e){}
     }
}

output of this program is that, first the content of file1.txt is printed and then content of file2.txt is printed on console.

PipedInputStream & PipedOutputStream classes:-
                     -These are also high level streams. These streams will work in the multithreaded environment. Before using these streams we have to connect then together. As any content written in the output stream immediately that content will be moved into the PipedInputStream.

Constructor:-
(1) public PipedInputStream()
(2) public PipedInputStream(PipedOutputStream out)
(3) public PipedOutputStream()
(4) public PipedOutputStream(PipedInputStream in)

Note:- 2nd and 4th constructor will used to connect the streams together.

Methods:-

public void connect(PipedInputStream in)
              -method of PipedOutputStream.
public void connect(PipedOutputStream out)
             -method of PipedInputStream.

Comments

  1. please let me know,is my article is helpful for you or not.
    thanks for response in advance.....

    ReplyDelete

Post a Comment

Popular posts from this blog

Reflection in java

define System.out.println()?