14:IOStreams



Stream:-   Continuous flow of data from one place to another.
IOStream:-    It is a flow of data between system and resources(peripherals),used to transfer the data
                          between  system and resources.
To transfer the data, we have to represent the data interns of its low level equivalent. i.e. either in the form of “byte(8bits)” or “characters(16 bits)”.  In java.io package classes are provided for us which supports to transfer the data. The classes in java.io package are categorized into two types.
1.   Byte oriented classes
a.   Read the data ------ InputStream
 DataInputStream
 FileInputStream
b.   Write the data------ OutputStream
 DataOutputStream
 FileOutputStream
2.   Character oriented classes
a.   Read the data------ Reader
FileReader
b.   Write the data------Writer
FileWriter
InputStream:-    It is a super class of all the classes, which supports to “Read” the data in the form of “bytes”.
OutputStream:-     It is a super class of all the classes, which supports to “Write” the data in the form of “bytes”.
Reader:-   Reader is a super class of all the classes, which supports to “Read” the data in the form of “characters”.
Writer:-   It is a super class of all the classes, which supports to “Write” the data in the form of “characters”.
Identifying the classes:-
If there is a “Stream” as part of a class name, then we can recognize the class as “byte oriented class”.
If there is a “Reader or Writer” as part of a class name, then we can recognize that class as “character oriented class”.
To read the data or to write the data , we need the address of the source or address of the destination.
We can provide this addresses using object of classes.
Q) which classes are provides address of source or destinations?
          Some classes as part of java.io package provides the address of source or destination.
Q) How can we make these  address available to IOStream classes?
          For all the classes in java.io package, we have constructors are defined to accepts address of source or destination.
Program:-   To print the content on the console.

import java.io.PrintStream;
public class print {
public static void main(String args[])   {
//PrintStream ps =new PrintStream();
//we can’t create the object of OutputStream, because it is abstract class.
//PrintStream  ps = new PrintStream(new OutputStream(){write(){---------}});
         

OutPut:

My content
PrintStream ps =new PrintStream(System.out);

//address of destination

ps.println("my content");

//ps.println() is same as the System.out.println()
}  }


Explanation:-
In this program we have written a code to write the data on the console.
PrintStream class constructor is define to accept OutputStream object(destination address).
We can’t create OutputStream class object, because it is abstract class. So, we can create object Anonymous inner class.
Program:-  
import java.io.DataInputStream;
import java.io. InputStream;
class ReadContent   {
public static void main(String args[])throws Exception   {
//InputStream is = new InputSt();
//address of source expecting.
// we can’t create the object of InputStream, because it is a abstract class.
OutPut:
enter some data::
suji
the result is::
suji
         
DataInputStream dis = new DataInputStream(System.in);
System.out.println("enter some data::");
String str = dis.readLine();
System.out.println("the result is::");
System.out.println(str);
}   }

readLine():-   readLine() is implemented by using a thread to wait until we press enter keyword on  
                        keyboard.This method returns String.
and Actually  readLine () was implemented to Read the content in the form of  bytes converts that bytes into string.  Here the readLine() of DataInputStream class is deprecated, they have provide an alternative methods in the place of deprecated methods.
import java.io.BufferedReader;
import java.io.InputStreamReader;
class ReadCon  {
          public static void main(String[] args)throws Exception   {

//InputStreamReader isr = new InputStreamReader(System.in);
//BufferedReader br = new BufferedReader(isr);
//instead of writing the above two lines we can write only one line as below. If we are using object only once, then we will directly create without any reference variable.


BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//expecting address of source. Here address of source is reader class object.
Output:
enter some data:
suji
the result is:
suji
//we can’t create object of Reader because of it is abstract.
//we can create the object of its subclass is InputStreamReader.
System.out.println("enter some text:");
String str = br.readLine();
System.out.println("the result is:");
System.out.println(str);
}  }
Steps to follow to write the data Into a file:-
1.   Take the data into a String(Read it from console here).
2.   Convert that String into byte array using getBytes().
3.   Create FileOutputStream object and call the write() of it.
OutPut:
input please:
Hai Hello
[B@192d342
[B@192d342
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
 public class Writefile  {
public static void main(String args[])  {
try    {
System.out.println("input please:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String data = br.readLine();
byte[]   bytes = data.getBytes();
System.out.println(bytes);
FileOutputStream fos = new FileOutputStream("file1.txt");
//To write the data into a file.when above statement is executed file will be opened.
fos.write(bytes);
System.out.println(bytes);
fos.close();
 }catch(Exception ex)  {
System.out.println(ex.getMessage());
}  }   }
Explanation:-
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String data = br.readLine();
The above code is used to read the data from console. To write this into a file we are using a FileOutputStream. Which can be used to write the data into a file in the form  of bytes.
So, we are converting the data into byte array and calling write() of “fos”.
FileOutputStream fos = new FileOutputStream(“file1.txt”);
When this statement is executed JVM will check for the file with given name (file1.txt).
If it is not there it will create the new one, otherwise it will make use of the same file, which is already there.
When above statement is executed file will be opened to write the content. When we open a file always cursor will be at the beginning of the file (zeroth file).
fos.write(bytes) when this method is executed data will be transferred to the file and will be written from the beginning of a file.
 If we write some other data during execution in second time it will be overwritten.
FileOutputStream fos = new FileOutputStream(“file1.txt”,true);
When we use this statement cursor will be placed at the end of the file and the text we are entered will be append from the EOF. Its avoiding overwriting a file.
Note:-  according to coding standards, if any resource is append as part of our program it has to be closed at the end of the program.
Program:- To read the data from file in the form of bytes.
import java.io.FileInputStream;
public class Readfile  {
public static void main(String args[])  {

OutPut:

output before read()method :_

output afterread()method :
Hai Hello
try {
FileInputStream fis = new FileInputStream ("file1.txt");
int size = fis.available();
//number of bytes available in a file, size of bytes.
String data = null;
byte[] bytes = new byte[size];
data = new String(bytes);
System.out.println("output before read()method :"+data);
fis.read(bytes);
data = new String(bytes);
System.out.println("output after read()method :"+data);
fis.close();
}catch(Exception ex)  {
}   }
  }

import java.io.*;
public class writeData  {
public static void main(String args[])  {
try  {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("input please:");
String data = br.readLine();
FileWriter fw = new  FileWriter("my file.doc",true);
//it will be opened a file.
char  ch[] = data.toCharArray();    // string to char[]
OutPut:
input please:
Hai
written data into a file
fw.write(ch);   //write data to file.
System.out.println("written data into a file");
fw.close();
 }catch(Exception ex)  {
}   }
}
Program:-  to write the data to the file in the form of characters.
Explanation:-
FileWriter  is used here to write the data into a file. Previously we used FileOutputStream to write the data in the form of bytes.
There we have converted the string into byte array. Here we have to convert the string into character array.
When fw.write(ch) is executed data will be written into the file character by character.
 FileWriter fw = new  FileWriter(“my file.doc”,true);
When we pass true here file pointer will moved to the EOF, that content will be appended to the content of existing file. When the file pointer is at the end of the file, then the ASCII value of file pointer is -1.
Program:-   To read the data from a file in the form of characters.
import java.io.FileReader;

public class ReadData   {
public static void main(String args[])   {
try   {
          FileReader fr = new FileReader("myfile.doc");
          String data="itargetit";
          int i=fr.read();
//read each character of a file, when file pointer reaches to the end, then ASCII value of file pointer is -1.
while(i!=-1) {
          char c = (char)i;
          data=data+c;
          i=fr.read();
} System.out.println("result is :"+data);   
} catch(Exception ex) {
}finally {
}  } }
RandomAccessFile:-
It is used to read and write the contents in all the mode(read mode, write mode, read and write mode).


Seek():-
          Seek(long pos) ---à sets the file pointer offset, measured from the beginning of this file at which the next read and write occurs.
length():-
          it is used to return the length(size) of the file.
Program:-

//mode=”r” //read mode
//mode=”w” //write mode
// mode =”rw” //read and write mode
import java.io.*;
public class RandomFile  {
          RandomAccessFile raf;
BufferedReader br;
int id;
String name;
float sal;
RandomFile()  {
try    {
                   br=new BufferedReader(new InputStreamReader(System.in));
             }catch(Exception ex)  {
Output:-

enter id:
5
enter name
jhg
enter sal
6876
your entered data is writen to the file

          }}
public void readDataFromConsole()  {
try  {
          System.out.println("enter id:");
id=Integer.parseInt(br.readLine());
System.out.println("enter name");
name = br.readLine();
System.out.println("enter sal");
sal=Float.parseFloat(br.readLine());
          }catch(Exception ex)  {
          }  }
public void writeFile()  {
try   {
          readDataFromConsole();
          raf=new RandomAccessFile("ramfile.txt","rw");
raf.writeInt(id);
raf.writeUTF(name);
raf.writeFloat(sal);
System.out.println("your entered data is writen to the file");
          }catch(Exception ex)   {
                   System.out.println(ex.getMessage()); } }
public static void main(String args[])  {
RandomFile rf = new RandomFile();
rf.writeFile();
}  }


Serialization:- process of writing the state of an object into a byte stream which is known as serialization.
“State of an object” means data present in the object at any instance of time.
Transferring the data contained in the object from RAM to hard disk is known as Serialization.
Transferring the data from RAM to other resource of the same system or from RAM to resources of a system that are connected.
Java.io.Serializable is an interface provided by java soft people which supports serialization.
Tagged interface or marked interface:-
          An interface without any methods is known as tagged or marked interface.
Eg:- java.io.Serializable , java.lang.Clonable.
If any class is implementing serializable interface JVM will support to convert the state of object of those classes into a byte stream.
 That means only serializable objects can be serialized. That means objects of classes which are implementing serializable interface can be serialized.
In the below example we are writing the state of an object from to the file in hard disk.
Program:-

import java.io.Serializable;
import java.io.*;

Output:-

Success.
class Data1   {
          int val;
          String name;
          double salary;
          }
public class DataSe implements Serializable  {
          int id;
String name;
double sal;
public static void main(String args[])  {
          Data1 data = new Data1();
          data.val=432;
data.name="rani";
data.salary=34.00;
DataSe datase = new DataSe();
datase.id=500;
datase.name="rani";
datase.sal=340.00;
//want to write the state of this object into a file.
try   {
          FileOutputStream fos = new FileOutputStream("t.tmp");
          ObjectOutputStream oos = new ObjectOutputStream(fos);
          //oos.writeObject(data); it will give an error because this object class is not serializable.
          oos.writeObject(datase);  // dataset is serializable.
          String var="itargetit";
          oos.writeObject(var);
fos.close();
System.out.println("success");
}catch(Exception ex)  {
System.out.println("exception:"+ex.getMessage());
}  } }
Explanation:-
ObjectOutputStream(oos) class is used to write the data into a file. oos will accepts address of the destination.
This address we have to pass in the form of object of OutputStream class. But OutputStream class is an abstract class. So we can’t create an object of it. So we are creating fos and passing as an argument to oos.
writeObject() is a method using which we can write the state of an object into a file. here data will be transferred to file in the form of bytestream.
Deserialization:-  Process of reading the state of an object from the byte stream is known as Deserialization.
Program:-
import java.io.*;
class Datase1 implements Serializable{
          int id;
          String name;
          String sal;
}public class Deserial {      
public static void main(String args[])  {

// read the data(state of an object)from the file.

try {
FileInputStream fis = new FileInputStream("t.tmp");
ObjectInputStream ois= new ObjectInputStream(fis);
Object obj = ois.readObject();
Datase1 datase1 = (Datase1)obj;
System.out.println(datase1.id);
System.out.println(datase1.name);
System.out.println(datase1.sal);
System.out.println("successfull");

// this data contains state of the object which was serialized.

fis.close();
                   }catch(Exception ex)  {
                   System.out.println("exception:"+ex.getMessage());
          } } }
Program:-
import java.io.*;
class Filedemo  {
public static void main(String args[])  {
          File file = new File("E:/File/mybook.txt");
          //if there is a file it will make use of existing file, otherwise it will create a new file.
Output:-

false
file is created
mybook.txt
false
false
0
          boolean check = file.isFile();
System.out.println(check);
System.out.println("file is created");
System.out.println(file.getName());
boolean read = file.canRead();
System.out.println(read);      
boolean write = file.canWrite();
System.out.println(write);
long size = file.length();
System.out.println(size);
} }

No comments:

Post a Comment