Alphalearningschool
        

<<< Prev

Next >>>

Up
Java I/O

Java I/O  : -It is used to take input and produce output. Java uses the concept of stream to make input output operation fast. It is in java.io package. We can perform file handling in java by using i/o api.

Let’s start :

Tips : Before starting java i/o we should know about stream.

Stream :- Sequence of data is called stream. It is composed of bytes. We call it stream because data is also flowing continuously like water stream.

In java ,3 streams are created for us automatically.:-

  • out: standard output stream.
  • in: standard input stream.
  • System.err: standard error stream.

Java I/O  : -It is used to take input and produce output. Java uses the concept of stream to make input output operation fast. It is in java.io package. We can perform file handling in java by using i/o api.

Let’s start :

Tips : Before starting java i/o we should know about stream.

Stream :- Sequence of data is called stream. It is composed of bytes. We call it stream because data is also flowing continuously like water stream.

In java ,3 streams are created for us automatically.:-

  • out: standard output stream.
  • in: standard input stream.
  • System.err: standard error stream.
Print output and an error message to the console.

1.System.out.println("simple message");
2.System.err.println("error message");

To get input from console.

1.int i=System.in.read();//returns ASCII code of 1st character
System.out.println((char)i);//will print the character

 

OutputStream:- Java application uses  outputstream to write a data to the destination. It can be files, an array, peripheral device or socket.

InputStream :- Java applications uses outputstream to read data from the source.

Now we will see output and input stream by pictorial representations:

OutputStream: OutputStream is an abstract class. It is the superclass of all classes representing an output stream of bytes.Outputstream accepts output bytes and send them to sink.

Methods of outputstream:

Method

Description

1.public void write(int)throws IOException

is used to write a byte to the current output stream.

2.public void write(byte[])throws IOException

is used to write an array of byte to the current output stream.

3.public void flush()throws IOException

flushes the current output stream.

4.public void close()throws IOException

is used to close the current output stream.

Java FileOutputStream Class : It is used to write data to a file.

If you are writing primitive values to a file.use fileoutputstream class.we can write byte oriented as well as character oriented data through fileoutputstream class. But for character oriented data, it is preferred to use FileWriter.

Example :  Let's see the declaration for Java.io.FileOutputStream class:

public class FileOutputStream extends OutputStream

FileOutputStream class methods:

Method

Description

protected void finalize()

It is used to clean up the connection with the file output stream.

void write(byte[] ary)

It is used to write ary.length bytes from the byte array to the file output stream.

void write(byte[] ary, int off, int len)

It is used to write len bytes from the byte array starting at offset off to the file output stream.

void write(int b)

It is used to write the specified byte to the file output stream.

FileChannel getChannel()

It is used to return the file channel object associated with the file output stream.

FileDescriptor getFD()

It is used to return the file descriptor associated with the stream.

void close()

It is used to closes the file output stream.

Java FileOutputStream Example 1: write byte :
import java.io.FileOutputStream;  
public class FileOutputStreamExample {  
    public static void main(String args[]){    
           try{    
             FileOutputStream fout=new FileOutputStream("D:\\abc.txt");    
             fout.write(100);    //ascii value of d is 100
             fout.close();    
             System.out.println("success...");  //output d  
            }catch(Exception e){System.out.println(e);}    
      }    
} 

Java FileOutputStream example 2: write string :
import java.io.FileOutputStream;  
public class FileOutputStreamExample {  
    public static void main(String args[]){    
try{    
        	FileOutputStream fout=new FileOutputStream("D:\\abc.txt");    
            String s="Welcome to alphalearningschool";    
            byte b[]=s.getBytes();//converting string into byte array    
            fout.write(b);    
            fout.close();    
            System.out.println("success...");    
           }catch(Exception e){System.out.println(e);}    
     }    
} 

Java FileInputStream Class :  This class is used to obtain input bytes from a file. It is used to read byte oriented data  from a file, it may be picture, audio, video etc.We can also read a character stream data, but for reading character stream data better to use FileReader class.

Java FileInputStream class declaration : public class FileInputStream extends InputStream

Java FileInputStream class methods:

Method

Description

int available()

It is used to return the estimated number of bytes that can be read from the input stream.

int read()

It is used to read the byte of data from the input stream.

int read(byte[] b)

It is used to read up to b.length bytes of data from the input stream.

int read(byte[] b, int off, int len)

It is used to read up to len bytes of data from the input stream.

long skip(long x)

It is used to skip over and discards x bytes of data from the input stream.

FileChannel getChannel()

It is used to return the unique FileChannel object associated with the file input stream.

FileDescriptor getFD()

It is used to return the FileDescriptor object.

protected void finalize()

It is used to ensure that the close method is call when there is no more reference to the file input stream.

void close()

It is used to closes the stream.

 

Java FileInputStream example 1: read single character : 
import java.io.FileInputStream;  
public class DataStreamExample {  
     public static void main(String args[]){    
          try{    
            FileInputStream fin=new FileInputStream("D:\\abc.txt");   //file should be there.
            int i=fin.read();  
            System.out.print((char)i);    //It will read first character of txt file.
  
            fin.close();    
          }catch(Exception e){System.out.println(e);}    
         }    
        }

 

Java FileInputStream example 2: read all characters : 
import java.io.FileInputStream;  
public class DataStreamExample {  
     public static void main(String args[]){    
          try{    
            FileInputStream fin=new FileInputStream("D:\\abc.txt");    
            int i=0;    
            while((i=fin.read())!=-1){    
             System.out.print((char)i);    
            }    
            fin.close();    
          }catch(Exception e){System.out.println(e);}    
         }    
        }

 

Java BufferedOutputStream Class : This class is used for buffering an output stream. It internally uses buffer to store data it makes the performance fast because It adds more efficiency than to write data directly into a stream.

Syntax of BufferedOutputStream Class :

OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\\IO Package\\abc.txt"));

Java BufferedOutputStream class declaration : public class BufferedOutputStream extends FilterOutputStream 

Java BufferedOutputStream class constructors :

Constructor

Description

BufferedOutputStream(OutputStream os)

It creates the new buffered output stream which is used for writing the data to the specified output stream.

BufferedOutputStream(OutputStream os, int size)

It creates the new buffered output stream which is used for writing the data to the specified output stream with a specified buffer size.

 

Java BufferedOutputStream class methods : 

Method

Description

void write(int b)

It writes the specified byte to the buffered output stream.

void write(byte[] b, int off, int len)

It write the bytes from the specified byte-input stream into a specified byte array, starting with the given offset

void flush()

It flushes the buffered output stream.

 

Example of BufferedOutputStream class:
package com.alphalearning;  
import java.io.*;  
public class BufferedOutputStreamExample{    
public static void main(String args[])throws Exception{    
     FileOutputStream fout=new FileOutputStream("D:\\abc.txt");    
     BufferedOutputStream bout=new BufferedOutputStream(fout);    
     String s="Welcome to AlphaLearningschool";    
     byte b[]=s.getBytes();   
     bout.write(b);    
     bout.flush();    
     bout.close();    
     fout.close();    
     System.out.println("success");    
}    
} 

 

Java BufferedInputStream Class : java BufferedInputStream class is used to read information from stream. It internally uses buffer mechanism to make performance fast.

Java BufferedInputStream class declaration:public class BufferedInputStream extends FilterInputStream

Java BufferedInputStream class constructors :

Constructor

Description

BufferedInputStream(InputStream IS)

It creates the BufferedInputStream and saves it argument, the input stream IS, for later use.

BufferedInputStream(InputStream IS, int size)

It creates the BufferedInputStream with a specified buffer size and saves it argument, the input stream IS, for later use.

 

Java BufferedInputStream class methods: 

Method

Description

int available()

It returns an estimate number of bytes that can be read from the input stream without blocking by the next invocation method for the input stream.

int read()

It read the next byte of data from the input stream.

int read(byte[] b, int off, int ln)

It read the bytes from the specified byte-input stream into a specified byte array, starting with the given offset.

void close()

It closes the input stream and releases any of the system resources associated with the stream.

void reset()

It repositions the stream at a position the mark method was last called on this input stream.

void mark(int readlimit)

It sees the general contract of the mark method for the input stream.

long skip(long x)

It skips over and discards x bytes of data from the input stream.

boolean markSupported()

It tests for the input stream to support the mark and reset methods.

Java SequenceInputStream Example :
package com.alpha;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.SequenceInputStream;

public class OutputStream {
	 
		public static void main(String args[])throws Exception{    
			   FileInputStream input1=new FileInputStream("D:\\abc.txt");    
			   FileInputStream input2=new FileInputStream("D:\\abcd.txt");    
			   SequenceInputStream inst=new SequenceInputStream(input1, input2);    
			   int j;    
			   while((j=inst.read())!=-1){    
			    System.out.print((char)j);    
			   }    
			   inst.close();    
			   input1.close();    
			   input2.close();    
			  }    
			}

 

Example that reads the data from two files and writes into another file: 

package com.alpha;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.SequenceInputStream;

public class OutputStream {
	 
	public static void main(String args[])throws Exception{    
		   FileInputStream fin1=new FileInputStream("D:\\abc.txt");    
		   FileInputStream fin2=new FileInputStream("D:\\abcd.txt");    
		   FileOutputStream fout=new FileOutputStream("D:\\new.txt");      
		   SequenceInputStream sis=new SequenceInputStream(fin1,fin2);    
		   int i;    
		   while((i=sis.read())!=-1)    
		   {    
		     fout.write(i);        
		   }    
		   sis.close();    
		   fout.close();      
		   fin1.close();      
		   fin2.close();       
		   System.out.println("Success..");  
		  }    
		}

 

SequenceInputStream example that reads data using enumeration :  if we want to read more than two files we need enumeration. Enumeration object can be obtained by calling elements() method of the Vector class.

Example:

package com.alpha;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
import java.util.Enumeration;
import java.util.Vector;

public class OutputStream {
	 
	public static void main(String args[])throws IOException{    
		//creating the FileInputStream objects for all the files    
		FileInputStream fin=new FileInputStream("D:\\a.txt");    
		FileInputStream fin2=new FileInputStream("D:\\b.txt");    
		FileInputStream fin3=new FileInputStream("D:\\c.txt");    
		FileInputStream fin4=new FileInputStream("D:\\d.txt");    
		//creating Vector object to all the stream    
		Vector v=new Vector();    
		v.add(fin);    
		v.add(fin2);    
		v.add(fin3);    
		v.add(fin4);              
		//creating enumeration object by calling the elements method    
		Enumeration e=v.elements();      
		//passing the enumeration object in the constructor    
		SequenceInputStream bin=new SequenceInputStream(e);    
		int i=0;      
		while((i=bin.read())!=-1){    
		System.out.print((char)i);    
		}     
		bin.close();    
		fin.close();    
		fin2.close();    
		}//output :     
		}

Java ByteArrayOutputStream Class :This class is used to write common data to multiple files. In this stream data is written into bytes array  later we can write it into multiple streams. The ByteArrayOutputStream holds a copy of data and forwards it to multiple streams. The buffer of ByteArrayOutputStream automatically grows according to data.

Java ByteArrayOutputStream class declaration :public class ByteArrayOutputStream extends OutputStream 

Java ByteArrayOutputStream class constructors :

Constructor

Description

ByteArrayOutputStream()

Creates a new byte array output stream with the initial capacity of 32 bytes, though its size increases if necessary.

ByteArrayOutputStream(int size)

Creates a new byte array output stream, with a buffer capacity of the specified size, in bytes.

 

Java ByteArrayOutputStream class methods:

Method

Description

int size()

It is used to returns the current size of a buffer.

byte[] toByteArray()

It is used to create a newly allocated byte array.

String toString()

It is used for converting the content into a string decoding bytes using a platform default character set.

String toString(String charsetName)

It is used for converting the content into a string decoding bytes using a specified charsetName.

void write(int b)

It is used for writing the byte specified to the byte array output stream.

void write(byte[] b, int off, int len

It is used for writing len bytes from specified byte array starting from the offset off to the byte array output stream.

void writeTo(OutputStream out)

It is used for writing the complete content of a byte array output stream to the specified output stream.

void reset()

It is used to reset the count field of a byte array output stream to zero value.

void close()

It is used to close the ByteArrayOutputStream.

 

Example of Java ByteArrayOutputStream :

package com.alpha;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
public class OutputStream {
	 
	public static void main(String args[])throws Exception{    
	      FileOutputStream fout1=new FileOutputStream("D:\\a.txt");    
	      FileOutputStream fout2=new FileOutputStream("D:\\b.txt");    
	        
	      ByteArrayOutputStream bout=new ByteArrayOutputStream();    
	      bout.write(100);  //ascii value  of d is 100 
	      bout.writeTo(fout1);    
	      bout.writeTo(fout2);    
	        
	      bout.flush();    
	      bout.close();//has no effect    
	      System.out.println("Success...");    
	     }    
	    } 

 

Java ByteArrayInputStream Class :The  ByteArrayInputStream is composed of two words. ByteArray and InputStream. According to name it is used to read byte array as input stream.

In this class contains an internal buffer which is used to read byte array as stream. In this stream, the data is read from a byte array. It automatics grow according to data.

Java ByteArrayInputStream class declaration :  public class ByteArrayInputStream extends InputStream

Example of Java ByteArrayInputStream :

import java.io.*;  
public class ReadExample {  
  public static void main(String[] args) throws IOException {  
    byte[] buf = {64,63,62,61};  
    // Create the new byte array input stream  
    ByteArrayInputStream byt = new ByteArrayInputStream(buf);  
    int k = 0;  
    while ((k = byt.read()) != -1) {  
      //Conversion of a byte into character  
      char ch = (char) k;  
      System.out.println("ASCII value of Character is:" + k + "; Special character is: " + ch);  
    }  
  }  
} 

 

Java DataOutputStream Class : Java DataOutputStream class allows an application to write primitive Java data types to the output stream in a machine-independent way. This java application generally uses the data output stream to write data that can later be read by a data input stream.

Java DataOutputStream class declaration : public class DataOutputStream extends FilterOutputStream implements DataOutput

Example of DataOutputStream class :

import java.io.*;

public class FileOutput {

	public static void main(String[] args) throws IOException {
		FileOutputStream f=new FileOutputStream("D:\\abcd.txt");  
		DataOutputStream d=new DataOutputStream(f);
		d.writeInt(65);
		d.flush();
		d.close();
	System.out.println("success.");//Output : It will write A in abcd text file.
}
}

 

Java DataInputStream Class : This class allows an application to read primitive data from input stream in a machine independent way. This is generally used to write data that can be read by DataInputStream.

Java DataInputStream class declaration : public class DataInputStream extends FilterInputStream implements DataInput

Example of DataInputStream class :

import java.io.*;

public class FileOutput {
		public static void main(String[] args) throws IOException {  
 InputStream input = new FileInputStream("D:\\abc.txt"); //file should be there. 
		    DataInputStream inst = new DataInputStream(input);  
		    int count = input.available();  
		    byte[] ary = new byte[count];  
		    inst.read(ary);  
		    for (byte bt : ary) {  
		      char k = (char) bt;  
		      System.out.print(k+"-"); //it will print one by one like abc =a-b-c 
		    }  
		  }  
		} 

 

Java FilterOutputStream Class : This class implements the OutputStream class.It provides different subclasses like BufferedOutputStream and DataOutputStream to provides additional functionality. We use less times of this class.

Java FilterOutputStream class declaration : public class FilterOutputStream extends OutputStream

Example of FilterOutputStream class : 

import java.io.*;

public class FileOutput {
		public static void main(String[] args) throws IOException {  
			File file=new File("D:\\abc.txt");
		  FileOutputStream data=new FileOutputStream(file);
		  FilterOutputStream fil=new FilterOutputStream(data);
		  String s="Alphalearning school";
		  byte b[]=s.getBytes(); 
		  fil.write(b);
		  fil.flush();
		  fil.close();
		  data.close();
		  System.out.println("success..");
			
		    }  
		  }

 

Java FilterInputStream Class : This class implements the InputStream class.It provides different subclasses like BufferedInputStream and DataInputStream to provides additional functionality. We use less times of this class.

Java FilterInputStream class declaration : public class FilterInputStream extends InputStream

Example of FilterInputStream class :

import java.io.*;
public class FileOutput {
		public static void main(String[] args) throws IOException {  
		File file=new File("D:\\abc.txt");
		  FileInputStream data=new FileInputStream(file);
		  FilterInputStream fil=new BufferedInputStream(data);
		  int k=0;
		  while((k=fil.read())!=-1) {
			  System.out.print((char)k);
		  }
		    }  
		  }

 

Java ObjectStreamClass : ObjectStreamClass act as a Serialization descriptor for class. This class contains the name and serialVersionUID of the class.

Example: 
import java.io.ObjectStreamClass;  
import java.util.Calendar;  
  
public class ObjectStreamClassExample {  
    public static void main(String[] args) {  
  
        // create a new object stream class for Integers  
        ObjectStreamClass osc = ObjectStreamClass.lookup(Laptop.class);  
  
        // get the value field from ObjectStreamClass for integers  
        System.out.println("" + osc.getField("price"));  
  
        // create a new object stream class for Calendar  
        ObjectStreamClass osc2 = ObjectStreamClass.lookup(String.class);  
  
        // get the Class instance for osc2  
        System.out.println("" + osc2.getField("hash"));  
  
    }  
} 

 

Java ObjectStreamField class : A description of a Serializable field from a Serializable class. An array of ObjectStreamFields is used to declare the Serializable fields of a class. 

The java.io.ObjectStreamClass.getField(String name) method gets the field of this class by name.

Example:

import java.io.ObjectStreamClass;  
import java.util.Calendar;  
  
public class ObjectStreamClassExample {  
     public static void main(String[] args) {  
             
          // create a new object stream class for Integers  
          ObjectStreamClass osc = ObjectStreamClass.lookup(String.class);  
  
          // get the value field from ObjectStreamClass for integers  
          System.out.println("" + osc.getField("value"));  //null
  
          // create a new object stream class for Calendar  
          ObjectStreamClass osc2 = ObjectStreamClass.lookup(Calendar.class);  
  
          // get the Class instance for osc2  
          System.out.println("" + osc2.getField("isTimeSet"));  //Z isTimeSet
  
       }  
}

 

Java Console Class : This class is used to take input from console, It provides methods to read texts and password. If we will read password text through console it will not visible to user.The java.io.Console class is attached with system console internally.

Java Console class declaration : public final class Console extends Object implements Flushable

Example:

import java.io.*;
class Console
{
    public static void main(String args[]) 
    {
        String str;
        //Obtaining a reference to the console.
        Console con = System.console();
         
        // Checking If there is no console available, then exit.
        if(con == null) 
        {
            System.out.print("No console available");
            return;
        }
         
        // Read a string and then display it.
        str = con.readLine("Enter your name: ");
        con.printf("Here is your name: %s\n", str);
 
        //to read password and then display it
        System.out.println("Enter the password: ");
        char[] ch=con.readPassword();
 
        //converting char array into string
        String pass = String.valueOf(ch);
        System.out.println("Password is: " + pass);
    }
}

 

Java FilePermission Class : In this class all is about  permission to read and write a file or a directory.All permission are related to path like:

1.C:\\inputoutput\\-: It indicates that the permission is associated with all sub directories and files recursively.

2 C:\\inputoutput\\*: It indicates that the permission is associated with all directory and files within this directory excluding sub directories.

Java FilePermission class declaration: public final class FilePermission extends Permission implements Serializable

Example:

import java.io.Console;
import java.io.FilePermission;
import java.io.IOException;
import java.security.PermissionCollection;

public class Check2 {
	public static void main(String[] args) throws IOException {
		String srg = "D:\\IO Package\\abc.txt";
		FilePermission file1 = new FilePermission("D:\\IO Package\\-", "read");
		PermissionCollection permission = file1.newPermissionCollection();
		permission.add(file1);
		FilePermission file2 = new FilePermission(srg, "write");
		permission.add(file2);
		if (permission.implies(new FilePermission(srg, "read,write"))) {
			System.out.println("Read, Write permission is granted "
					+ "for the path " + srg);
		} else {
			System.out.println("No Read, Write permission is granted"
					+ " for the path " + srg);
		}
	}
}

Java Writer: It is an abstract class for writing character stream. The methods that a subclass must implement are write(char[], int, int), flush(), and close(). Most subclasses will override some of the methods defined here to provide higher efficiency, functionality or both.

Java Writer Example :

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class Check{
	  public static void main(String[] args) {  
	        try {  
	            Writer w = new FileWriter("D:\\output.txt");  
	            String content = "I love my country";  
	            w.write(content);  
	            w.close();  
	            System.out.println("Done");  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        }  
	    }  
	}  //Content will be in destination.

 

Java Reader: It is an abstract class for reading character streams.It is same as like writer. After writing through this class we can read characters.

Some of the implementation class are BufferedReader, CharArrayReader, FilterReader, InputStreamReader, PipedReader, StringReader.

Example:

import java.io.FileReader;
import java.io.Reader;


public class Check {
		      public static void main(String[] args) {  
		          try {  
		              Reader reader = new FileReader("D:\\abc.txt");  
		              int data = reader.read();  
		              while (data != -1) {  
		                  System.out.print((char) data);  
		                  data = reader.read();  
		              }  
		              reader.close();  
		          } catch (Exception ex) {  
		              System.out.println(ex.getMessage());  
		          }  
		      }  // abc.txt file text will be the Output.
		  }

 

Java FileWriter Class : It is used to write character-oriented data to a file. It is character-oriented class which is used for file handling in java. It provides methods to write string directly. In this we do not have to convert string into byte array.

Java FileWriter class declaration :  public class FileWriter extends OutputStreamWriter 

Example:

import java.io.FileWriter;
public class Check {
	public static void main(String args[]){    
        try{    
          FileWriter fw=new FileWriter("D:\\abcd.txt");    
          fw.write("hello");    
          fw.close();    
         }catch(Exception e){System.out.println(e);}    
         System.out.println("Success...");    
    }    
}

Java FileReader Class : This class is used to read data from the file. It will return data in byte format like fileinputstream class. It is character-oriented class which is used for file handling in java.

Java FileReader class declaration : public class FileReader extends InputStreamReader.

Example:

import java.io.FileReader;
public class Check{
	 public static void main(String args[])throws Exception{    
         FileReader fr=new FileReader("D:\\abcd.txt");    
         int i;    
         while((i=fr.read())!=-1)    
         System.out.print((char)i);    
         fr.close();    
   }    
}

 

Java BufferedWriter Class : This class is used to provide buffering for writer instances. It makes our performance fast. It inherits writer class. The buffering characters are used for providing the efficient writing of single arrays, characters, and strings.

Class declaration: public class BufferedWriter extends Writer. 

Example of Java BufferedWriter :

import java.io.BufferedWriter;
import java.io.FileWriter;
public class Check {
	public static void main(String[] args) throws Exception {     
	    FileWriter writer = new FileWriter("D:\\abc.txt");  
	    BufferedWriter buffer = new BufferedWriter(writer);  
	    buffer.write("hello");  
	    buffer.close();  
	    System.out.println("Success");  
	    }  
	} 

 

Java BufferedReader Class : This class is used to read text from a character based input stream.It can be used to read data line by line by readline() method. It makes the performance .

Java BufferedReader class declaration : public class BufferedReader extends Reader

Example:

import java.io.BufferedReader;
import java.io.FileReader;
public class Check{
	public static void main(String args[])throws Exception{    
        FileReader fr=new FileReader("D:\\abcd.txt");    
        BufferedReader br=new BufferedReader(fr);    

        int i;    
        while((i=br.read())!=-1){  
        System.out.print((char)i);  
        }  
        br.close();    
        fr.close();    
  }    
}

 

Example of reading data from console by InputStreamReader and BufferedReader : 

import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Check2{
	public static void main(String args[])throws Exception{             
	    InputStreamReader r=new InputStreamReader(System.in);    
	    BufferedReader br=new BufferedReader(r);            
	    System.out.println("Enter your name");    
	    String name=br.readLine();    
	    System.out.println("Welcome "+name);  
      }  
}  

 

Example of reading data from console until user writes stop : 

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Check2{
	public static void main(String args[])throws Exception{             
	     InputStreamReader r=new InputStreamReader(System.in);    
	     BufferedReader br=new BufferedReader(r);           
	     String name="";    
	     while(!name.equals("stop")){    
	      System.out.println("Enter data: ");    
	      name=br.readLine();    
	      System.out.println("data is: "+name);    
	     }              
	    br.close();    
	    r.close();    
	    }    
	    }

 

Java CharArrayReader Class : This class is composed of two words CharArray and Reader .This is used to read Character array as a reader. It inherits Reader class.

Java CharArrayReader class declaration : public class CharArrayReader extends Reader 

Example:

import java.io.CharArrayReader;
public class Check2{
	 public static void main(String[] ag) throws Exception {  
		    char[] ary = {'A', 'l', 'p', 'h', 'a'};  
		    CharArrayReader reader = new CharArrayReader(ary);  
		    int k = 0;  
		    // Read until the end of a file  
		    while ((k = reader.read()) != -1) {  
		      char ch = (char) k;  
		      System.out.print(ch + " : ");  
		      System.out.println(k);  
		    }  
		  }  
		}

 

Java CharArrayWriter Class :This class is used to write common data to multiple files. This is also inherits from writer class. Its buffer will automatically grow if when data is written in stream. If we will call close() method it will not effect on the object.

Java CharArrayWriter class declaration :  public class CharArrayWriter extends Writer 

Example:

import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.FileWriter;
public class Check2{
	public static void main(String args[])throws Exception{    
        CharArrayWriter out=new CharArrayWriter();    
        out.write("Hello Everyone");    
        FileWriter f1=new FileWriter("D:\\a.txt");    
        FileWriter f2=new FileWriter("D:\\b.txt");    
        FileWriter f3=new FileWriter("D:\\c.txt");    
        FileWriter f4=new FileWriter("D:\\d.txt");    
        out.writeTo(f1);    
        out.writeTo(f2);    
        out.writeTo(f3);    
        out.writeTo(f4);    
        f1.close();    
        f2.close();    
        f3.close();    
        f4.close();    
        System.out.println("Success...");    
       }    
      }

Java PrintStream Class : This class provides methods to write data to another stream. The printStream class automatically flash the data so there is no need to call flush() method. Also it’s methods do not throw  exception.

Declaration of java PrintStream Class: public class PrintStream extends FilterOutputStream implements Closeable. Appendable  

Example :

import java.io.FileOutputStream;
import java.io.PrintStream;
public class Check2{
	 public static void main(String args[])throws Exception{    
           FileOutputStream fout=new FileOutputStream("D:\\abcd.txt ");    
		   PrintStream out=new PrintStream(fout);    
		   out.println(2018);    
		   out.println("Hello");    
		   out.println("Hi");    
		   out.close();    
		   fout.close();    
		  System.out.println("Success...");    
                          int a=20; //example of printing integer value by format specifier using printf() method of java.io.PrintStream class. 
System.out.printf("%d",a); //output – 20  without io exception we can write.
		 }    
		}

 

Java PrintWriter class : This  class is the implementation of Writer class. It is used to print the formatted representation of objects to the text-output stream.

Class declaration of Java PrintWriter classpublic class PrintWriter extends Writer 

Example:

import java.io.File;
import java.io.PrintWriter;
public class Check2{
	public static void main(String[] args) throws Exception {  
        //Data to write on Console using PrintWriter  
 PrintWriter writer = new PrintWriter(System.out);    
 writer.write("Hello");
 //System.out.println("sucesss.dsdfsdsds.");
 writer.flush();  
 writer.close(); 

//Data to write in File using PrintWriter       
 PrintWriter writer1 =null;      
    writer1 = new PrintWriter(new File("D:\\abcd.txt"));  
    writer1.write("Writting data..............");                                                   
    System.out.println("sucesss..");
    writer1.flush();  
    writer1.close(); 
}  
} 

 

Java OutputStreamWriter : This  class is used to convert character stream to byte stream, the characters  are encoded into byte using a specified charset. write() method calls the encoding converter which converts the character into bytes.

Example :

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class Check2{
	 public static void main(String[] args) {  
		  
	        try {  
	            OutputStream outputStream = new FileOutputStream("D:\\abcd.txt");  
	            Writer outputStreamWriter = new OutputStreamWriter(outputStream);  
	            outputStreamWriter.write("Hello World");  
	            outputStreamWriter.close();
	            System.out.println("success...");
	        } catch (Exception e) {  
	            e.getMessage();  
	        }  
	    }  
	}

Java InputStreamWriter : An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset.

Example:

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
public class Check2{
	 public static void main(String[] args) {  
		 try  {  
	            InputStream stream = new FileInputStream("D:\\abcd.txt");  
	            Reader reader = new InputStreamReader(stream);  
	            int data = reader.read();  
	            while (data != -1) {  
	                System.out.print((char) data);  
	                data = reader.read();  
	            
	            }  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	    }  
	}

 

Java PushbackInputStream Class : This class is a character stream reader.It is used to pushes back a character into stream and overrides the filter reader class.

Class Declaration : public class PushbackReader extends FilterReader

Example:

import java.io.*;  
public class ReaderExample{  
    public static void main(String[] args) throws Exception {  
        char ary[] = {'1','-','-','2','-','3','4','-','-','-','5','6'};  
        CharArrayReader reader = new CharArrayReader(ary);   
        PushbackReader push = new PushbackReader(reader);  
        int i;  
            while( (i = push.read())!= -1) {  
                if(i == '-') {  
                    int j;  
                    if( (j = push.read()) == '-'){  
                         System.out.print("#*");  
                    }else {  
                        push.unread(j); // push back single character  
                        System.out.print((char)i);  
                    }  
                }else {  
                        System.out.print((char)i);  
                }  
           }         
    }  
}  
Output : 1
#*2-34#*-56

 

Java StringWriter Class : This class is a character stream that collects output from string buffer, which can be used to construct a string. The StringWriter class inherits the Writer class.

Example:

import java.io.BufferedReader;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import java.io.StringWriter;

public class Check2{
	 public static void main(String[] args) throws IOException {  
	        char[] ary = new char[512];  
	        StringWriter writer = new StringWriter();  
	        FileInputStream input = null;  
	        BufferedReader buffer = null;  
	        input = new FileInputStream("D://abcd.txt");  
	        buffer = new BufferedReader(new InputStreamReader(input, "UTF-8"));  
	        int x;  
	        while ((x = buffer.read(ary)) != -1) {  
	                   writer.write(ary, 0, x);  
	        }  
	        System.out.println(writer.toString());        
	        writer.close();  
	        buffer.close();  
	    }  
	}

 

Java StringReader Class : This class is a character stream with string as a source.It changes into characters streams while we pass string.

Example :

import java.io.StringReader;
public class Check2{
	   public static void main(String[] args) throws Exception {  
	        String srg = "Hello World \n New line.";  
	        StringReader reader = new StringReader(srg);  
	        int k=0;  
	            while((k=reader.read())!=-1){  
	                System.out.print((char)k);  
	            }  
	        }  
	} 

 

Java FilterWriter And FilterReader: This class is used to write filtered characters streams. This is an abstract class. Java FilterReader is used to read text according to our guidance.

Example:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilterWriter;
import java.io.IOException;
import java.io.Writer;


class CustomFilterWriter extends FilterWriter {  
    CustomFilterWriter(Writer out) {  
        super(out);  
    }  
    public void write(String str) throws IOException {  
        super.write(str.toLowerCase());  
    }  
}  
public class Check2 {  
    public static void main(String[] args) {  
        try {  
            FileWriter fw = new FileWriter("D:\\abcd.txt");   
            CustomFilterWriter filterWriter = new CustomFilterWriter(fw);             
            filterWriter.write("HELLO WORLD");  
            filterWriter.close();  
            FileReader fr = new FileReader("D:\\abcd.txt");  
            BufferedReader bufferedReader = new BufferedReader(fr);  
            int k;  
            while ((k = bufferedReader.read()) != -1) {  
                System.out.print((char) k);  
            }  
            bufferedReader.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  Output : hello world
} 

 

Java File Class : It is an abstract representation of files and directory pathname. In this we can do many operations on files and like create,delete,modify,rename etc.