Pages

Java.IO Package input stream and output stream Deep Concept





This package contains the input/output facilities (i.e classes) that are used to read input or write output

Stream


A stream is a collection of memory cells.

A stream is connected to a data source or a device like  a file, keyboard, network computer, monitor, printer

A stream is the mediator between the datasource/device   and a program, i.e the program reads data from the stream or the program writes the data to the stream.

Stream



Inputstream.


The stream from which the program reads the data is called inputstream



Outputstream.


The stream to which the program writes data is called outputstream
Streams in java.


Streams in java are objects of the relevant stream classes.



For example


BufferedInputStream is a stream class
BufferedOutputStream is a stream class
BufferedInputStream bis;
BufferedOutputStream bout; 

bis and bout are objects (stream objects).
All stream classes are a part of "java.io" package



Types of streams

There are two types
(i) Byte streams
(ii)Character streams


Byte streams are used to read and write binary data (8 bits data)

Character streams are used to read and write character data (supports reading and writing 16 bits character data)
The super classes of Byte stream category

InputStream  and  OutputStream

The super classes of character stream category

Reader  and Writer
few class names
BufferedReader
BufferedWriter
FileReader 
FileWriter
BufferedInputStream 
FileInputStream
FileOutputStream


The input stream "System.in" is connected to k/b.

the "InputStreamReader" class. Object of this class is used convert bytes to characters.
the "BufferedReader" class. This is the subclass of "Reader" used to read from buffer.


Presentation11

the "read()" method .
This method is a member of "InputStream" and "Reader" classes.
This is used to read one character from the stream  and return an int.
This method throws IOException

when the end of stream is reached this method returns -1

Example
import java.io.*;
    class ReadDemo
    {  
        public static void main(String args[]) throws Exception
        {  

            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter few characters (CTRL-C to stop)");
            int i=0;
            do
            {
                i = br.read();
                if(i != -1)  
                    Sop((char)i);
            } while(i != -1);

        }
    }
   

Example
import java.io.*;
    class ReadLineDemo
    {  
        public static void main(String args[]) throws Exception
        {  

            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            int num1=0,num2=0;
            String temp="";
            System.out.println("Enter first number");
            temp = br.readLine();

            num1 = Integer.parseInt(temp);
            System.out.println("Enter other number");
            temp = br.readLine();

            num2 = Integer.parseInt(temp);
            Sop(num1+num2);

            System.out.println("Enter few characters (CTRL-C to stop)");
            int i=0;
            do
            {
                i = br.read();
                if(i != -1)  
                    Sop((char)i);
            } while(i != -1);

        }
    }


The "FileInputStream" and "FileOutputStream" classes

These are used in working with files.
import java.io.*;
class FileCopy
{
    public static void main(String args[]) throws Exception
    {

        FileInputStream in = new FileInputStream("test.txt");
        FileOutputStream out = new FileOutputStream("test2.txt");
        int i=0;
        do
        {
            i = in.read();
            if(i != -1)
                out.write(i);
        } while(i!=-1);
        System.out.println("file copied...");
    }
}
}


The  "DataInputStream" and "DataOutputStream" classes
These are used to read and write primitive data types like int, char and  float etc
DataInputStream class contains methods like readInt(),readByte()  etc for reading int s , byte s
DataOutputStream class contains methods like writeInt(), writeByte() etc for writing int s, byte s import java.io.*;

class DIS
    {
        public static void main(String args[]) throws Exception
        {
            DataInputStream in = new DataInputStream(System.in);

            DataOutputStream  out = new DataOutputStream(System.out);
            System.out.println("Enter a number ");
            int x= in.readInt();
            out.writeInt(x);
        }
    }


Object's state.
An object's state is the data of instance variables of an object

For example
Student s1 = new Student();
   s1.sno=10;
   s1.sname="srini";

the values of "sno" and "sname"  (10 and srini) of "s1" are together called as object's state

Serialization.

It is the process of saving an object's state to a storage
The "java.io.Serializable" interface
This interface has no methods. interfaces which contain no methods are called marker interfaces.
only objects those classes which implement "Serializable" interface can be serialized



the "java.io.ObjectInputStream" class and "java.io.ObjectOutputStream" class
These classes contain the methods used to read a serialized object and write an object's state toa storage

Example.

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("student.ser"));
ObjectInputStream in = new ObjectInputStream(new FileInputStream("student.ser"));

the "readObject()" and "writeObject()" methods of the "ObjectInputStream" and "ObjectOutputStream"  classes
These methods are used to read an object and write an object

Example.
   
 Student s1= new Student();
    s1.sno=10; s1.sname="Ravi";
   
     out.writeObject(s1);
     Student s = (Student) in.readObject();


assuming that "out" and "in" are objects of "ObjectOutputStream" and "ObjectInputStream" classes

import java.io.*;
    class Student implements Serializable
    {
        int studentNo;
        String studentName;
        Student(){}
        Student(int studentNo,String studentName)
        {
            this.studentNo = studentNo;
            this.studentName = studentName;
        }
        void printStudent()
        {
            System.out.println(studentNo+":"+studentName); }   
    }

    class SerializeDemo
    {
        public static void main(String args[]) throws Exception
        {
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("student.ser"));

            Student s1 = new Student(10,"Ravi");
            out.writeObject(s1);
            System.out.println("object Serialzed..");
            System.out.println("read that object from another program...");
        }
    }


import java.io.*;
    class ReadSerializedObject
    {
        public static void main(String args[]) throws Exception
        {
            ObjectInputStream in = new ObjectInputStream(newFileInputStream("student.ser"));

            Student s1 = (Student) in.readObject();
            s1.printStudent(); 
        }
    }
   

The "transient" keyword
if we declare a variable using this keyword, then that variable will not serialized

ex
    class Student
    {
      int sno;
      transient int marks;
// not serialized     }

static variables are NOT SERIALIZED if a class implements "Serializable" interface then all its subclasses automatically become serializable

ex
    class A implements Serializable
   {   }

   class B extends A {   }
   class C extends B {   }

 class B and C automatically become serializable

the "NotSerializableException" class
if a class contains an object of other class that is NOT IMPLEMENTING the "Serializable" interface and if we try to serialize the source object that we get an exception called "NotSerializableException" at runtime

ex.
    class A {  }
   class B implements Serializable
   {
     A a1 = new A();  // exception      A a2; // no exception only reference     transient A a3=new A(); // no exception
                          //because transient
  }



The "java.io.Externalizable" interface

This interface extends the "Serializable" interface and declares two methods "readExternal()" and "writeExternal()"
This interface and its methods are used to control serialization. i.e we can write custom code in "readExternal()" and "writeExternal()" methods which are automatically executed when "readObject()" and "writeObject()" are executed.

class A implements Externalizable
    {
        public void readExternal() throws IOException,ClassNotFoundException
        { 
            some code
        }

        public void writeExternal() throws IOException,ClassNotFoundException
        {
            some code
        }
    }
    A a1 = new A();
    out.writeObject(a1);
    A temp = (A) in.readObject();



the "java.io.PrintWriter" class
This is a subclass of "Writer"
This is a convenient class for writing output

ex.
     PrintWriter pw = new PrintWriter(System.out,true);
     pw.println("hello");

No comments:

Post a Comment