Input Output in Java (io package)

<< Previous Chapter Next Chapter >>
Input Output in Java (Java io package):

Input / output is a technique in java or in any other programming languages through which we can program of any language with input or output device. This is required to take input from and to give out put to the input / output devices.

Stream – a stream is a buffer in memory which is connected with input / output device. It is s flow of bytes. This is basically used to increase the performance of the program. Moving a single character at a time from program to input output devices is not a suggestible idea. Instead collect all data in a buffer memory and move all at one go. This buffer area is termed as stream.
As a real example shifting home from one location to another, instead of moving each items one by one, hire a vehicle, put all into it and move everything at one go.





In java’s GUI based applications we never use stream, this is only used in either console base or networking applications.

High level design of stream classes in java:



List of mostly used java classes in io:

1) FileInputStream                  FileOutputStream
2) ByteArrayInputStream       ByteArrayOutputStream
3) BufferedInputStream          BufferedOutputStream
4) DataInputStream                DataOutputStream
5) PipedInputStream               PipedOutputStream
6) SequenceInputStream       NA
7) ObjectInputStream             ObjectOutputStream
8) PrintStream                                    StringTokenizer (until package)

Reader (Character Stream):
1) FileReader                          FileWriter
2) BufferedReader                  BufferedWriter
3) CharArrayReader               CharArrayWriter
4) InputStreamReader            OutputStreamWriter

PrintWriter and Scanner are also used in input / output but these does not belongs to above hierarchy. They are from java.util package.


Create a .txt file at e:\javaio\myFile.txt and create a java file MyFileWriter.java inside dev21century.io package:

package dev21century.io;

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

public class MyFileWriter {

     public static void main(String[] args) {

           /*Start writing to file */
           try {
                FileOutputStream fw = new FileOutputStream(new File("e:\\javaio\\myFile.txt"));
                String msg = "save tree go green";
                byte msgCh[] = msg.getBytes();
                for(int i=0;i<msgCh.length;i++)
                {
                     fw.write(msgCh[i]);
                }
                fw.close();
                System.out.println("File created successfully.");
               
           } catch (FileNotFoundException e) {
                System.out.println(e);
           }
           catch(IOException e)
           {
                System.out.println(e);
           }
           /*End writing to file */
          
           /*Start reading file */
           try {
                FileInputStream fr = new FileInputStream("e:\\javaio\\myFile.txt");
                int i = 0;
                while((i=fr.read()) != -1)
                {
                     System.out.print((char)i);
                }
                fr.close();
               
           } catch (FileNotFoundException e) {
                System.out.println(e);
           }
           catch(IOException e)
           {
                System.out.println(e);
           }
          
           /*End reading file */
          
     }
}
Output:

PipedInput and PipedOutputStream:

Example:
package dev21century.io;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

class PipedOutput implements Runnable
{
       PipedOutputStream pout;
       PipedOutput(PipedOutputStream pout)
       {
              this.pout = pout;
       }
      
       public void run()
       {
              for(int i = 65;i<=91;i++)
              {
                     try{
                           pout.write(i);
                           Thread.sleep(1000);
                     }
                     catch(Exception e){System.out.println(e);}
              }
       }
}

class PipedInput implements Runnable
{
       PipedInputStream pin;
       PipedInput(PipedInputStream pin)
       {
              this.pin = pin;
       }
       public void run()
       {
              int z = 0;
              for(int i=65;i<=91;i++)
              {
                     try{
                           z = pin.read();
                     }
                     catch(Exception e) {  }
                     System.out.print((char)z + " ");
              }
       }
}

public class Prun
{
       public static void main(String args[]) throws IOException
       {
              PipedOutputStream pout = new PipedOutputStream();
              PipedInputStream pin = new PipedInputStream();
              pout.connect(pin);
              PipedOutput po = new PipedOutput(pout);
              PipedInput pi = new PipedInput(pin);
             
              Thread thread1 = new Thread(po);
              Thread thread2 = new Thread(pi);
              thread1.start();
              thread2.start();
       }
}

Output:


Sequence input stream:
It takes more than one input stream and gives one by one e.g. it accepts 5 files and combine them in one.
It uses Enumeration interface to take multiple input Objects.
For example, create 3 files at e:\javaio folder myFile1.txt, myFile2.txt and myFile3.txt and write some contents in it. Create a java file SequenceInput.java in dev21century.io package:

package dev21century.io;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.util.Enumeration;
import java.util.Scanner;

public class SequenceInput {

       public static void main(String[] args)
       {
              try{
              //SequenceInputStream sin = new SequenceInputStream(new FileInputStream("e:\\javaio\\myFile1.txt"), new FileInputStream("e:\\javaio\\myFile2.txt"));  //line number 14
              SequenceInputStream sin = new SequenceInputStream(new MyEnum());//line number 15
              Scanner scanner = new Scanner(sin);
                          
              String s = "";
              s = scanner.nextLine();
              System.out.println(s);
              }catch(Exception e)
              {
                     e.printStackTrace();
                     //System.out.println(e);
              }
       }     
}

class MyEnum implements Enumeration
{
       InputStream in[];
       int i = 0;
       MyEnum()
       {
              try{
                     in = new InputStream[]{new FileInputStream("e:\\javaio\\myFile1.txt"), new FileInputStream("e:\\javaio\\myFile2.txt"), new FileInputStream("e:\\javaio\\myFile3.txt")};

              }
              catch(Exception e) {System.out.println(e);}
             
       }
      
       public boolean hasMoreElements() {
              if(i<3)
                     return true;
              else
                     return false;
       }

       public Object nextElement() {
              return in[i++];
       }

}

Output:
The output will be the contents of all 3 files. Uncomment line number 14 and comment line number 15 and re run.

Serialization:
Definition – the process of converting object into a stream is known as serialization.
Deserialization is just its reverse, the process of converting a stream into an object.
Serialization is used for following 2 purposes:
1) To save the state of an object or for persisting the object.
2) To transfer the object into the network.
An objects property value is known as its state. Persisting an object means we are keeping it somewhere, so that it will be found as it is without any change in its value (or state).



Serializable is a marker interface which does not contain any methods, it just mark our class.

Rule 1 – whenever any object is de serialize then the constructor of that class is never called.
Rule 2 – if we do not want to save any non-static data via serialization process then we need to mark them as transient, because transient data members are never saved.

Example:

Emp.java:
package dev21century.io;

import java.io.Serializable;
class Base
{
       int z = 50;
}

public class Emp extends Base implements Serializable
{
       transient int a;
       static int b;
       String name;
       int age;
      
       Emp(String name, int age, int a, int b, int z)
       {
              this.name = name;
              this.age = age;
              this.a = a;
              this.b = b;
              this.z = z;
       }
}

MyClient1.java
package dev21century.io;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class MyClient1 {

       ObjectOutputStream dout;
       public MyClient1()
       {
              try{
                     Emp e1 = new Emp("Xyz Limited", 10, 5, 20, 50);
                     dout = new ObjectOutputStream(new FileOutputStream("e:\\javaio\\myFile1.txt"));
                     dout.writeObject(e1);
                     dout.flush();
              }
              catch(Exception e)
              {System.out.println(e);}
       }
       public static void main(String args[])
       {
              new MyClient1();
       }
      
}

MyServer.java:
package dev21century.io;

import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class MyServer {

       ObjectInputStream dis;
       MyServer()
       {
              try{
                     dis = new ObjectInputStream(new FileInputStream("e:\\javaio\\myFile1.txt"));
                     Emp z = (Emp)dis.readObject();
                     System.out.println("Name: " + z.name);
                     System.out.println("Age: " + z.age);
                     System.out.println("a = " + z.a);
                     System.out.println("b = " + z.b);
                     System.out.println("z = " + z.z);
              }
              catch(Exception e){
              System.out.println(e);
              }
       }
       public static void main(String args[])
       {
              new MyServer();
       }
}

First execute the MyClient.java file and then MyServer.java. Output will be:


Just notice that values of a and b are zero, because a is transient and b is static.

Character Stream:
File Name: MyFileWriter.java

package dev21century.io;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class MyFileWriter {
   public static void main(String[] args) {
      /*start writing file*/
       try {
         FileWriter fw = new FileWriter("e:\\javaio\\myFile2.txt");
         String s = "save tree go green.";
          char ch[] = s.toCharArray();
                    
          for(int i =0;i<ch.length;i++)     //line no. 17
            fw.write(ch[i]);           //line no. 18
                    
            //fw.write(ch);                   //line no. 20
            //fw.write(s);                    //line no. 21
                    
            fw.close();
                    
                    
         } catch (IOException e) {
                     e.printStackTrace();
         }
      
         /*start reading file*/
         try {
             FileReader fr = new FileReader("e:\\javaio\\myFile2.txt");
             int i = 0;
             while((i=fr.read())!=-1)
               System.out.print((char)i);
                    
             fr.close();
                    
          } catch (Exception e) {
                     e.printStackTrace();
       }
             
   }
}


Output:
Make sure file does exists at e:\javaio\myFile2.txt

Also, try to comment line no 17 and 18 and uncomment 20 and then 21, and rerun the program it will work.

Char Array Reader & Char Array Writer:

File Name: MyCharArray.java:
package dev21century.io;

import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.FileWriter;
import java.io.IOException;

public class MyCharArray {

       public static void main(String[] args) {

              try {
              CharArrayWriter fw = new CharArrayWriter();
              String s = "save tree & water go green";
              char ch[] = s.toCharArray();
              for(int i = 0;i<ch.length;i++) //line no 16
                     fw.write(ch[i]);         //line no 17
             
              //fw.write(ch);                //line no 19
              fw.writeTo(new FileWriter("e:\\javaio\\myFile3.txt"));
              System.out.println(fw.toString());
              char z[] = fw.toCharArray();
                    
              CharArrayReader fr = new CharArrayReader(z);
              int i =0;
              while((i=fr.read()) != -1)
                     System.out.print((char)i);
                    
              } catch (IOException e) {
                     e.printStackTrace();
              }
       }
}

Output:


Also, try to comment line no 16 and 17 and uncomment line no 19, and rerun the program it will work.

StringTokenizer:
StringTokenizer is used to read the string randomly instead of byte by byte, here we will give this stream to another, stream will divide it in pieces of streams which is known as token, it will provide a delimiter:

File Name: MyStringTokenizer.java
package dev21century.io;

import java.util.StringTokenizer;
public class MyStringTokenizer {

       public static void main(String[] args) {

              String s = "product=car;model=accord;company=honda";
              StringTokenizer st = new StringTokenizer(s, "=;");
              while(st.hasMoreElements())
              {
                     System.out.println(st.nextToken());
              }
       }
}
Output:

Similar operation we can perform using Scanner class, lets take Scanner example, then we will see the difference between them:

package dev21century.io;

import java.util.Scanner;
import java.util.StringTokenizer;
public class MyStringTokenizer {

       public static void main(String[] args) {

              Scanner s = new Scanner(System.in);
              int i = s.nextInt();
              double d = s.nextDouble();
              float f1 = s.nextFloat();
              long l1 = s.nextLong();
              System.out.println(i + l1 + f1 + d);
              String s1 ="";
              while(!s1.equals("stop"))
              {
                     s1 = s.nextLine();
                     System.out.println(s1);
              }
       }
}

Output:

Difference between StringTokenizer and Scanner:
1) In Scanner class, the delimiters are predefined we cannot change. They are 1) newline 2) space 3) tab 4) white space.
We can add Scanner with any stream, keyboard file etc.

File class:
This class is mainly used to interact with operating system used to represent any file or folder of hard disk.

File f1 = new File("e:\\javaio");
File f2 = new File("e:\\javaio","myFile1.txt");
File f3 = new File("e:\\javaio\\myFile1.txt");
File f4 = new File(f1, "myFile1.txt");
             
boolean b1 = f1.exists();
boolean b2 = f2.exists();
boolean b3 = f3.exists();


<< Previous Chapter Next Chapter >>





No comments:

Post a Comment