Skip to content

FileWriter

Constructors

  1. FileWriter fw = new FileWriter(String name);
  2. FileWriter fw = new FileWriter(File f);
  3. FileWriter fw = new FileWriter(String name, boolean append);
  4. FileWriter fw = new FileWriter(File f, boolean append);

Constructors listed 1 and 2 overrides the existing data, but Constructors listed 3 and 4 appends to existing data.

If no file is available, this will create that file.

Methods

  1. write (int ch)
  2. to write a single character to the file.

    fw.write(100); // Unicode value for d is 100
    fw.write('d'); // Both writes d.
    
  3. write(char[] ch)

  4. write(String s)
  5. flush()
  6. To guarantee our data including last char also on written property.
  7. close()

Examples

FileWriter Demo

import java.io.*;

class FileWriterDemo {
    public static void main(String[] args) {
        try {
            FileWriter fw = new FileWriter("abc.txt");
            fw.write(100);
            fw.write("abc \n Software");
            // Paragraph Break
            fw.write('\n');
            // Character Array
            char[] ch = { 'a', 'b', 'c' };
            // Writing character array
            fw.write(ch);
            fw.write('\n');
            fw.flush();
            fw.close();
        } catch (IOException error) {
            error.printStackTrace();
        }
    }
}

FileWriter Append Demo

import java.io.*;

class FileWriterAppendDemo{
    public static void  main(String[] args){
        try{
            // Appends
            FileWriter fw = new FileWriter("abc.txt",true);

            fw.write("\n Arjun");
            fw.flush();
            fw.close();
        }catch(IOException error ){
            error.printStackTrace();
        }
    }
}