File Writer

Class FileWriter

java.lang.Object
  extended by java.io.Writer
      extended by java.io.OutputStreamWriter
          extended by java.io.FileWriter

All Implemented Interfaces:

File Writer object is used to write character data into a file

Constructors:

Lets see the constructor's available in FileWriter class

1. FileWriter fw=new FileWriter(String name);
    /* Constructs a FileWriter object given a file name*/

2. FileWriter fw=new FileWriter(String name, boolean append);
    /* Constructs a FileWriter object given a File object.*/

3. FileWriter fw=new FileWriter(File f);
    /* Constructs a FileWriter object given a File object.*/

4. FileWriter fw=new FileWriter(File f, boolean append);
   /*Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written*/

5. FileWriter fw=new FileWriter(fileDescriptor fd);
   /* Constructs a FileWriter object associated with a file descriptor*/

Method Summary
 
Methods inherited from class java.io.OutputStreamWriter
 
Methods inherited from class java.io.Writer
 
Methods inherited from class java.lang.Object
 

Most Frequently Used Methods

1. write (int char) : To write a single character to the file.

2. write (String s) : To write a string to the file.

3. write (char [] ch) : To write all the characters present in the char [].

4. flush() : To make sure data is added to the file.

5. close() : Close the file.

Now lets see the functionality of the above methods with an example

package com.java.everythingaboutselenium;
import java.io.*;

public class FileRead{

   public static void main(String args[])throws IOException{

      File file = new File("Hello1.txt");
      // creates the file
      file.createNewFile();
      // creates a FileWriter Object
      FileWriter writer = new FileWriter(file); 
      // Writes the content to the file
      writer.write("This\n is\n an\n example\n"); 
      writer.flush();
      writer.close();

      //Creates a FileReader Object
      FileReader fr = new FileReader(file); 
      char [] a = new char[50];
      fr.read(a); // reads the content to the array
      for(char c : a)
          System.out.print(c); //prints the characters one by one
      fr.close();
   }
}