Java IO Streams

 

JAVA IO STREAMS

 

Streams
Java programs perform I/O operations through streams. A stream is a sequence of data. It is an abstraction that either produces or consumes information. A stream is linked to a physical device by the Java I/O system. All streams represent an input source and an output destination and they behave in the same manner, even if the actual physical devices to which they are linked differ.
 
Byte Streams and Character Streams
Java defines two types of streams: byte streams and character streams. Byte streams are used for handling binary data. Character streams are used for handling input and output of characters in Unicode.

 



IO STREAM

 

Byte streams
Byte streams are defined using two class hierarchies. At the top are two abstract classes InputStream and OutputStream. These two classes have several subclasses to handle different types of physical devices such as disk files, network connections, memory buffers etc., The most important methods of these classes are read() and write() for reading and writing bytes of data.

 



 BYTE STREAM

 

Character streams
Character streams are defined using two class hierarchies. At the top are two abstract classes Reader and Writer. These two classes handle Unicode character streams. The most important methods of these classes are read() and write() for reading and writing characters of data

 



 

CHARACTER STREAM


 

An example file handling program to demonstrate byte and character streams.
// Byte stream
// Using InputStream and OutputStream classes
// File copy program
/*
Note: Byte stream reads data from file in its ASCII form.
Typecast to char when writing to new file.
*/
import java.io.*;
import java.lang.*;
import java.util.*;
 
class IO_Demo
{
     public static void main(String as[]) throws IOException
     {
          FileInputStream fin = null;
          FileOutputStream fout = null;
          int i;
         
          try
          {
              fin = new FileInputStream("ipt.txt");
              fout = new FileOutputStream("opt.txt");
              while(true)
              {
                   i = fin.read();
                   if(i==-1)
                        break;
                   fout.write((char)i);                             
              }
          }
          catch(Exception e)
          {
              System.out.println(e);
          }
          finally
          {
              if(fin!=null)
                   fin.close();
              if(fout!=null)
                   fout.close();
              System.out.println("File copied.");
          }
     }
}
 
// Character stream
// Using Reader and Writer classes
// Read from console and write to file
 
import java.io.*;
 
class RW
{
     public static void main(String as[]) throws IOException
     {
          BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
          FileWriter fw = null;
          try
          {
              fw = new FileWriter("opt.txt");
              int i = 0;
              while(i<3)
              {
                   String str = br.readLine().trim();
                   fw.write(str+"\n");
                   i++;
              }
          }
 
          catch(Exception e)
          {
              System.out.println(e);
          }
          finally
          {
              if(fw!=null)
                   fw.close();  
              System.out.println("\nEnd of program.");
          }
     }
}

Stack DS

 /* 

Classes and objects

Stack data structures 

*/


import java.io.*;

import java.util.*;


class StkDS

{

int tos, capacity;

int [] Stk;


public StkDS(int c)

{

tos = -1;

capacity = c;

Stk = new int[capacity];

}

int size()

{

return tos+1;

}

boolean isFull()

{

return((tos+1) == capacity);

}

boolean isEmpty()

{

return (tos==-1);

}

void push(int x)

{

if(!isFull())

Stk[++tos]=x;

else

System.out.print("\nFull stack. Cant insert element.");

}

void pop()

{

if(!isEmpty())

tos--;

else

System.out.print("\nEmpty stack. Cant delete element.");

}

int topandpop()

{

if(!isEmpty())

return(Stk[tos--]);

else

{

System.out.print("\nEmpty stack. Cant delete element.");

return -1;

}

}

void peek()

{

if(!isEmpty())

System.out.print("\nElement on top of stack is "+Stk[tos]); 

else

System.out.print("\nEmpty stack. No element present.");

}

void fnDisplay()

{

if(!isEmpty())

{

System.out.print("\nElements in stack : ");

for(int i=0;i<=tos;i++)

System.out.print(Stk[i]+" ");

}

else

System.out.println("\nEmpty stack. No elements present. ");

}

}


class StackDS

{

public static void main(String []as)throws IOException

{

Scanner sc = new Scanner(System.in);

System.out.print("\nEnter stack size : ");

int cap = sc.nextInt();

StkDS s = new StkDS(cap);

int choice;

do

{

System.out.print("\nMenu: 1. Push\t2. Pop\t3. TopandPop\t4. Peek\t5. Exit");

System.out.print("\nEnter choice : ");

choice = sc.nextInt();

switch(choice)

{

case 1: System.out.print("\nEnter element : ");

int ele=sc.nextInt();

s.push(ele);

s.fnDisplay();break;

case 2: s.pop();s.fnDisplay();break;

case 3: int val=s.topandpop();

System.out.println("\nDeleted element : "+val);

s.fnDisplay();break;

case 4: s.peek();s.fnDisplay();break;

case 5: System.exit(0);

}

}while(true);

}

}

Selection Sort

 

// 4. Selection Sort

import java.io.*;

import java.util.*;

 

class SelectionSort

{

     public static void main(String [] as) throws IOException

     {

          Scanner sc = new Scanner(System.in);

          int i, j, pos, arrlen, tmp;

         

          System.out.print("Enter array length : ");

          arrlen = sc.nextInt();

         

 

          System.out.println("Enter array elements : ");

          int arr[] = new int[arrlen];

          for(i=0;i<arrlen;i++)

              arr[i]=sc.nextInt();

         

          // Sorting

          for(i=0;i<arrlen-1;i++)

          {

              pos=i;

              for(j=i+1;j<arrlen;j++)

              {

                   if(arr[j]<arr[pos])

                        pos=j;

              }

              tmp=arr[pos];

              arr[pos] = arr[i];

              arr[i] = tmp;

          }

             

          System.out.print("Sorted array : ");

          for(i=0;i<arrlen;i++)

              System.out.print(arr[i]+"  ");

         

     }

}

Insertion sort

 

// 3. Insertion sort

import java.io.*;

import java.util.*;

 

class InsertionSort

{

     public static void main(String [] as) throws IOException

     {

          Scanner sc = new Scanner(System.in);

          int i, j, arrlen, tmp;

         

          System.out.print("Enter array length : ");

          arrlen = sc.nextInt();

         

          System.out.println("Enter array elements : ");

          int arr[] = new int[arrlen];

          for(i=0;i<arrlen;i++)

              arr[i]=sc.nextInt();

         

          // Sorting

          for(i=1;i<arrlen;i++)

          {

              tmp = arr[i];

              for(j=i;j>0;j--)

              {

                   if(tmp>arr[j-1])

                        break;

             

                   arr[j] = arr[j-1];

              }

              arr[j] = tmp;

          }

             

          System.out.print("Sorted array : ");

          for(i=0;i<arrlen;i++)

              System.out.print(arr[i]+"  ");

         

     }

}


Binary search

 

// 2. Binary search

import java.io.*;

import java.util.*;

 

class BinarySearch

{

     public static void main(String [] as) throws IOException

     {

          Scanner sc = new Scanner(System.in);

          int i, ele, arrlen, pos=-1;

          int top, bottom, mid;

         

          System.out.print("Enter array length : ");

          arrlen = sc.nextInt();

         

          System.out.println("Enter array elements : ");

          int arr[] = new int[arrlen];

          for(i=0;i<arrlen;i++)

              arr[i]=sc.nextInt();

         

          System.out.print("Enter element to search : ");

          ele = sc.nextInt();

         

          // Sort the input array

          Arrays.sort(arr);

         

          System.out.print("Entered array (sorted) : ");

          for(i=0;i<arrlen;i++)

              System.out.print(arr[i]+"  ");

         

          bottom = 0;

          top = arrlen-1;

 

          while(true)

          {

              if (bottom > top)

              {

                   System.out.println("\nElement not found in array.");

                   break;

              }

                  

              mid = (int)(bottom+top)/2;

 

              if(arr[mid] == ele)

              {

                   System.out.println("\nElement present in array.");

                   break;

              }

             

              else if (arr[mid] < ele)

                   bottom = mid + 1;

 

              else

                   top = mid - 1;

          }

     }

}

Sequential search

 

// 1. Sequential search

import java.io.*;

import java.util.*;

 

class SequentialSearch

{

     public static void main(String [] as) throws IOException

     {

          Scanner sc = new Scanner(System.in);

          int i, ele, arrlen, pos=-1;

         

          System.out.print("Enter array length : ");

          arrlen = sc.nextInt();

         

          System.out.println("Enter array elements : ");

          int arr[] = new int[arrlen];

          for(i=0;i<arrlen;i++)

              arr[i]=sc.nextInt();

         

          System.out.print("Enter element to search : ");

          ele = sc.nextInt();

         

          for(i=0;i<arrlen;i++)

          {

              if(arr[i]==ele)

              {

                   pos = i+1;

                   break;

              }

          }

         

          System.out.print("Entered array is : ");

          for(i=0;i<arrlen;i++)

              System.out.print(arr[i]+"  ");

         

          if(pos!=-1)

              System.out.print("\nElement found at position "+pos);

          else

              System.out.println("\nElement not found in array");

     }

}