Skip to main content

Java I/O Stream - FileReader and Writer , BufferedReader and Writer

Java I/O Stream

Input Stream: Taking input data from other source in your program.
Output Stream: Your program giving some data to other source.
Note: Other source can be another java program, console, file or any other program.
Task 1st:Take input character from console and print it on console.
Java input output classes belongs to java.io package and by default each and every class in java have java.lang package. java.lang package contains System class, which we use for print something on console like
System.out.println("Hello World");
if you open System class src code, you will find system class has a PrintStream type variable with name out and this PrintStream class belongs to java.io package have method println(String arg), which print passed argument in print method on console.

I/O variables of System Class:

  1. System.out: use for giving output to console. Type: PrintStream
  2. System.in: taking input from console. Type: InputStream

import java.io.IOException;

public class MainApp {

 public static void main(String[] args) {
  
  try {
   System.out.println("Give Input:");
    //it will read only one char
   //returns ASCII code of 1st character  
   int i = System.in.read();
   System.out.println(i);
   
   //convert ASCII code in char
   char c = (char)i;
   System.out.println(c);
   
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

import java.io.IOException;
//Example to read whole sentence
//till you press Enter
import java.io.IOException;

public class MainApp {

 public static void main(String[] args) {
  
  try {
   System.out.println("Give Input:");
   while(true){
    int i = System.in.read();
    
    //Key Enter ASCII code is 13
    //so when Enter get pressed loop will break 
    if(i==13){
     break;
    }
    
    char c = (char)i;
    //using print method to print each char in same line
    System.out.print(c);
   }
   
   
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

File Reader And File Writer

File

File class let you to create file object in java, It can be use in read a existing file or create a new file and write on file. File class also use for directories (folder) operations.

Syntax:
File file = new File("path/file.txt");

FileReader

FileReader class use for read file. FileReader is a type of InputStreamReader, its open a input stream and read from stream character by character.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;


public class FileTest {
 
 private void readFile() {

     //creating File Object
  //arg: file path with file name which you want to read
  File file = new File("D:/java/basic/file.txt");
  
  try {
   //file reader throws FileNotFoundException Exception
   FileReader fileReader = new FileReader(file);
   
   //reading file character by character 
      while(true){
       //read method throws IOException
      int i = fileReader.read();
         char c = (char)i;
         System.out.print(c);
         if(i==-1){
          break;
         }
      }
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 
 public static void main(String[] args) {
  FileTest ft = new FileTest();
  ft.readFile();
 }
} 

FileWriter

FileWriter class give you functionality to write on file. FileWriter type of OutputStreamWriter, its open a output stream and write on file character by character.

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;


public class FileTest {

 
 private void writeFile() {
  
  File file = new File("D:/file1.txt");
  
  //if file not exist creating a new file
  if(!file.exists()){
   try {
    file.createNewFile();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
  
  try {
   //writing on file
   FileWriter fw = new FileWriter(file);
   
   //here you giving string to write but internally write method 
   //write this sting char by char
   fw.write("This text written by java program.");
   
   //after writing it good to flush and close output stream
   //it will confirms your text get written on file and close 
   //the open resource 
   fw.flush();
   fw.close();
   
  } catch (IOException e) {
   e.printStackTrace();
  }

 }
 
 public static void main(String[] args) {
  FileTest ft = new FileTest();
  ft.writeFile();
 }

}

Buffered Reader and Buffered Writer

BuffredReader

BuffredReader class make reading from stream more efficient and fast, BuffredReader works on top of other lower reader class, its work as a CAP on other lower reader class.
Syntax:

BuffredReader br = new BuffredReader(reader);

BuffredReader use buffer memory (characters) that make fast and efficient reading.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

//BuffredReader Example
public class FileTest {
 
 private void readFile() {

  File file = new File("D:/java/basic/file.txt");
  
  try {
   //file redaer throws FileNotFoundException Exception
   FileReader fileReader = new FileReader(file);
   
   //BuffredReader object
   BufferedReader br = new BufferedReader(fileReader);
   
   String str = null;
   //reading file line by line
      while(true){
       
       //readLine returns line of file
       str = br.readLine();
       
       //no more line in file readline method will return null
       if(str==null){
        System.err.println("No more line to read");
        break;
       }
       
       //print line on console
       System.out.println(str);

      }
      
      //it will close file reader streem 
      br.close();
      
      
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 
 
 public static void main(String[] args) {
  FileTest ft = new FileTest();
  ft.readFile();
 }

}

BuffredWritter

BuffredWritter helps you to write on stream fast and efficient gives you more writing functionality and makes writing easy.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

//BuffredWritter Example
public class FileTest {

 
 private void writeFile() {
  
  File file = new File("D:/file1.txt");
  
  //if file not exist creating a new file
  if(!file.exists()){
   try {
    file.createNewFile();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
  
  try {
   //writing on file
   FileWriter fw = new FileWriter(file);
   
   BufferedWriter bw = new BufferedWriter(fw);
   
   bw.write("This text written by java program BufferedWriter.");
   
   //after writing it good to flush and close output stream
   //it will confirms your text get written on file and close
                        // the open resource 
   bw.flush();
   bw.close();
  } catch (IOException e) {
   e.printStackTrace();
  }

 }
 
 public static void main(String[] args) {
  FileTest ft = new FileTest();
  ft.writeFile();
 }

}

Comments

Popular posts from this blog

Java Array, Multi Dimensional Array, Anonymous Array and Arrays Util Class

Array An array is a index based container object. The length of an array fixed at time of array creation. An Array holds a fixed number of values of a single type . One Dimensional Array Array can be created by two ways. Syntex: //1st way arraytype[] name = new arraytype[length]; //2nd way arraytype name[] = new arraytype[length]; 1st way is more readable. Examples: //charecyter Array Example: //creating Array of char, length 5 char[] charArray = new char[5]; //Initialize array elements charArray[0] = 'H'; charArray[1] = 'E'; charArray[2] = 'L'; charArray[3] = 'L'; charArray[4] = 'O'; //creating Array of int, length 4 int[] intArray = new int[4]; //Initialize array elements intArray[0] = 2; intArray[1] = 0; intArray[2] = 1; intArray[3] = 5; //creating Array of string, length 7 String[] weeks = new String[7]; //Initialize array elements weeks[0] = "mon"; weeks[1] = "tue"; weeks[2] = "wed"; w

String - A story of very special class in java

String is most used java class in any java project. Java treated String as special class. Lets see, what so special in String. String Basics String is group of characters. char[] chrs = {'i',' ','a','m',' ','h','e','r','o','.'}; String str = new String(chrs); System.out.println(str); /* Output: i am hero. */ String is an immutable class. Immutable class:  A java class which object can not be modified if once created. Because String class is immutable, String is final in nature, its mean you can not modify string object once you created. Default value of string is null. Simplest way to initialize String is //object created in String Literal Pool String str = "hello world"; Above example known as String literal, All string literals in Java programs, such as "hello world", are object of String class. Another way to create String object is //object created in Heap m