FileWriter Class

FileWriter

This class can be used for writing character data to the file. It is not recommended to use the FileOutputStream class if we have to write any textual information as these are Byte stream classes.

Constructors
FileWriter fw = new FileWriter(String fname)
FileWriter fw = new FileWriter(File f); 

The above 2 constructors creates a file object to write character data to the file. If the file already contains some data it will overwrite with the new data. Instead of overriding if u have to perform append then we have to use the following constructors.

FileWriter fw = new FileWriter(String name, boolean append);
FileWriter fw = new FileWriter(File f, boolean append); 

If the underlying physical file is not already available then the above constructors will create the required file also.

Important methods

1. void write(int ch) throws IOException

For writing single character to the file.

2. void write(String s)throws IOException.

3. void write(char [] ch) throws IOException.

4. void flush()

To guaranteed that the last character of the data should be required to the file.

package com.ashok.files;

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

/**
 * 
 * @author ashok.mariyala
 *
 */
public class MyFile {
   public static void main(String arg[]) throws Exception {
      File f = new File("Ashok.txt");
      System.out.println(f.exists());
      FileWriter fw = new FileWriter(f, true);
      System.out.println(f.exists());
      fw.write(97);
      fw.write("Hai\nHow are you\n");
      char[] ch1 = { 'a', 'b', 'c' };
      fw.write(ch1);
      fw.flush();
      fw.close();
   }
}

Output

true
true

In Ashok.txt 
1st time
aHai
How are you
abc

2ndtime
aHai
How are you
abcaHai
How are you
abc
FileWriter Class


Scroll to top