FileReader and FileWriter Class in Java

"

Introduction to FileReader and FileWriter Classes in Java

The FileReader and FileWriter classes in Java are used for reading and writing text files, respectively. They are both character-oriented classes, which means that they read and write data one character at a time.

FileReader is used to read data from a text file, one character at a time.To create a FileReader object, you must pass the path to the file you want to read as a constructor argument.

FileWriter is used to write data to a text file, one character at a time. It can be used to write any type of text file, including text documents, HTML files, and XML files. To create a FileWriter object, you must pass the path to the file you want to write to as a constructor argument.

FileReader and FileWriter are very powerful classes for reading and writing text files in Java. They are used in a wide variety of applications, including text editors, web browsers, and database applications.


Here are some additional things to keep in mind when using FileReader and FileWriter:
  • Both FileReader and FileWriter are subclasses of the Reader and Writer classes, respectively. This means that they inherit all of the methods from these parent classes.
  • FileReader and FileWriter are both AutoCloseable classes. This means that they can be automatically closed using the try-with-resources statement.
  • If you are writing to a file that does not exist, FileWriter will create the file for you.
  • If you are writing to a file that already exists, FileWriter will overwrite the contents of the file.
  • To append data to an existing file, you can use the FileWriter constructor that takes a boolean parameter. If you set this parameter to true, FileWriter will append data to the end of the file instead of overwriting it.
Methods of FileReader Class
Method Description
close() Closes the FileReader object.
mark() Marks the current position in the FileReader object.
markSupported() Returns true if the FileReader object supports marking.
read() Reads a single character from the FileReader object.
read(char[] cbuf) Reads an array of characters from the FileReader object.
read(char[] cbuf, int off, int len) Reads an array of characters from the FileReader object, starting at the specified offset and reading the specified number of characters.
reset() Resets the FileReader object to the last marked position.
skip() Skips n characters in the FileReader object.
Methods of FileWriter Class
Method Description
close() Closes the FileWriter object.
flush() Flushes the data in the FileWriter object to the underlying file.
write(int c) Writes a single character to the FileWriter object.
write(char[] cbuf) Writes an array of characters to the FileWriter object.
write(char[] cbuf, int off, int len) Writes an array of characters to the FileWriter object, starting at the specified offset and writing the specified number of characters.
write(String str) Writes a string to the FileWriter object.
write(String str, int off, int len) Writes a portion of a string to the FileWriter object, starting at the specified offset and writing the specified number of characters.

Exercises

Write a program to read a Character from a file using FileReader Class in Java


  package javaprogrammingdemo;
  import java.io.File;
  import java.io.FileReader;
  import java.io.IOException;
  import java.util.*;
  public class javalabclass{
      public static void main(String args[]) {
          
        //Reading a Character from a file 
           
        try
        {    
          //filereader - read characters 
          FileReader fr = new FileReader("satish.txt");
          int data=fr.read();
          System.out.println((char)data);
          fr.close();
           
        }
        catch(IOException e)
        {
          System.out.println("check file");
        }
        catch(Exception e)
        {
          System.out.println("Exception caught here");
        }
        
        
      }
  } 

Write a program to read an Array of Characters from a File using FileReader Class in Java


package practiceproject;
import java.io.*;
import java.util.*;
public class democlass {
	
	 public static void main(String[] args) throws IOException {
       
		File obj = new File("satish.txt");
		FileReader fin = new FileReader(obj);
		char c[]=new char[4];
		fin.read(c);
		for(char k:c)
		{
			System.out.println(k);
		}
	 }
} 

Write a program to read characters into an array from a file using offset using FileReader Class in Java


  package practiceproject;
  import java.io.*;
  import java.util.*;
  public class democlass {
    
     public static void main(String[] args) throws IOException {
         
      File obj = new File("satish.txt");
      FileReader fin = new FileReader(obj);
      char c[]=new char[4];
      fin.read(c,1,2);
      for(char k:c)
      {
        System.out.println(k);
      }
     }
  } 

Write a Java Program to write a character to a file using FileWriter Class in Java


package practiceproject;
import java.io.*;
import java.util.*;
public class democlass {
	
	 public static void main(String[] args) throws IOException {
       
		File obj = new File("satish.txt");
		FileWriter fout = new FileWriter(obj);
		if(obj.canWrite())
		{
			fout.write('S');
		}
		fout.close();
	 }
} 

Write a Java Program write an array of characters to a file using FileWriter Class


  package practiceproject;
  import java.io.*;
  import java.util.*;
  public class democlass {
    
     public static void main(String[] args) throws IOException {
         
      File obj = new File("satish.txt");
      FileWriter fout = new FileWriter(obj);
      char c[]= {'s','a','t','i','s','h'};
      if(obj.canWrite())
      {
        fout.write(c);
      }
      fout.close();
     }
  } 

Write a Java Program to write a String to a file using FileWriter Class


package practiceproject;
import java.io.*;
import java.util.*;
public class democlass {
	
	 public static void main(String[] args) throws IOException {
       
		File obj = new File("satish.txt");
		FileWriter fout = new FileWriter(obj);
		String s = "satish is writing here";
		if(obj.canWrite())
		{
			fout.write(s);
		}
		fout.close();
	 }
}   

Write a Java Program to append data to a file using FileWriter Class


  package practiceproject;
  import java.io.*;
  import java.util.*;
  public class democlass {
    
     public static void main(String[] args) throws IOException {
       
       File obj = new File("output8.txt");
       FileWriter fout = new FileWriter(obj,true);
      try
      {
      
      String str="new message here";
      fout.write(str);
      System.out.println("file writing successful");
      }
      catch(Exception e)
      {
        System.out.println(e.getMessage());
      }
      finally
      {
        fout.close();
      }
     }
  }