FileWriter Class in Java - GeeksforGeeks

10 Feb, 2022
Java FileWriter class of java.io package is used to write data in character form to file. Java FileWriter class is used to write character-oriented data to a file. It is a character-oriented class that is used for file handling in java.
This class inherits from OutputStreamWriter class which in turn inherits from the Writer class.
The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.
FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream.
FileWriter creates the output file if it is not present already.
FileWriter extends OutputStreamWriter and Writer classes. It implements Closeable, Flushable, Appendable, AutoCloseable interfaces.
public class FileWriter extends OutputStreamWriter  
1. FileWriter(File file): It constructs a FileWriter object given a File object. It throws an IOException if the file exists but is a directory rather than a regular file does not exist but cannot be created, or cannot be opened for any other reason.
FileWriter fw = new FileWriter(File file);
2. FileWriter(File file, boolean append): It constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning. It throws an IOException if the file exists but is a directory rather than a regular file or does not exist but cannot be created, or cannot be opened for any other reason.
FileWriter fw = new FileWriter(File file, boolean append);
3. FileWriter(FileDescriptor fd): It constructs a FileWriter object associated with a file descriptor.
FileWriter fw = new FileWriter(FileDescriptor fd);
4. FileWriter(File file, Charset charset): It constructs the fileWriter when file and charset is given.
FileWriter fw = new FileWriter(File file, Charset charset);
5. FileWriter(File file, Charset charset, boolean append): It constructs the fileWriter when file and charset is given and a boolean indicating whether to append the data written or not.
FileWriter fw = new FileWriter(File file, Charset charset, boolean append);
6. FileWriter(String fileName): It constructs a FileWriter object given a file name.
FileWriter fw = new FileWriter(String fileName);
7. FileWriter(String fileName, Boolean append): It constructs a FileWriter object given a file name with a Boolean indicating whether or not to append the data written.
FileWriter fw = new FileWriter(String fileName, Boolean append);
8. FileWriter(String fileName, Charset charset): It constructs a FileWriter when a fileName and charset is given.
FileWriter fw = new FileWriter(String fileName, Charset charset);
9. FileWriter(String fileName, Charset charset, boolean append): It constructs a fileWriter when a fileName and a charset are given and a boolean variable indicating whether to append data or not.
FileWriter fw = new FileWriter(String fileName, Charset charset, boolean append);
Example:
Java
// Java program to create a text File using FileWriter  import java.io.FileWriter;import java.io.IOException;import java.util.*;class GFG {    public static void main(String[] args)        throws IOException    {        // initialize a string        String str = "ABC";        try {              // attach a file to FileWriter            FileWriter fw                = new FileWriter("D:/data/file.txt");              // read each character from string and write            // into FileWriter            for (int i = 0; i < str.length(); i++)                fw.write(str.charAt(i));              System.out.println("Successfully written");              // close the file            fw.close();        }        catch (Exception e) {            e.getStackTrace();        }    }}
 Output:
While creating a Java FileWriter, we can decide whether we want to append the file to an existing file, or we want to overwrite any existing file. This can be decided by choosing the appropriate constructor. The constructor for overwriting any existing file takes only one parameter that is a file name.
Writer fileWriter = new FileWriter("c:\\data\\output.txt");
The constructor for appending the file or overwriting the file, takes two parameters, the file name and a boolean variable which decides whether to append or overwrite the file
Writer fileWriter = new FileWriter("c:\\data\\output.txt", true);  // appends to file
Writer fileWriter = new FileWriter("c:\\data\\output.txt", false); // overwrites file
write(int a): This method writes a single character specified by int a.
write(String str, int pos, int length): This method writes a portion of the string from position pos until the length number of characters.
write(char ch[], int pos, int length): This method writes the position of characters from array ch[] from position pos till length number of characters.
write(char ch[]): This method writes an array of characters specified by ch[].
write(String st): This method writes a string value specified by ‘st’ into the file.
Java
// Java program to write text to file  import java.io.FileWriter;  public class GFG {      public static void main(String args[])    {          String data = "Welcome to gfg";          try {            // Creates a FileWriter            FileWriter output                = new FileWriter("output.txt");              // Writes the string to the file            output.write(data);              // Closes the writer            output.close();        }          catch (Exception e) {            e.getStackTrace();        }    }}
Output:
The file output.txt will contain "Welcome to gfg" text.
This method is used to get the type of encoding that is used for writing the data.
Java
// java program to show the usage// of getEncoding() function  import java.io.FileWriter;import java.nio.charset.Charset;  class Main {    public static void main(String[] args)    {          String file = "output.txt";          try {            // Creates a FileReader with default encoding            FileWriter o1 = new FileWriter(file);              // Creates a FileReader specifying the encoding            FileWriter o2 = new FileWriter(                file, Charset.forName("UTF11"));              // Returns the character encoding of the reader            System.out.println("Character encoding of o1: "                               + o1.getEncoding());            System.out.println("Character encoding of o2: "                               + o2.getEncoding());              // Closes the reader            o1.close();            o2.close();        }          catch (Exception e) {            e.getStackTrace();        }    }}
Output:
The character encoding of output1: Cp1253
The character encoding of output2: UTF11
In the above example, we have created 2 file writer named output1 and output2.
output1: does not specify the character encoding. Hence, the getEncoding() method returns the default character encoding.
output2: specifies the character encoding, UTF11. Hence, the getEncoding() method returns the specified character encoding.
After finishing writing characters to a FileWriter, we should close it. And this is done by calling the close() method.
 try {
     // Creates a FileReader with default encoding
     FileWriter o1 = new FileWriter(file);

     // Creates a FileReader specifying the encoding
     FileWriter o2 = new FileWriter(file, Charset.forName("UTF11"));

     // Returns the character encoding of the reader
     System.out.println("Character encoding of o1: " + o1.getEncoding());
     System.out.println("Character encoding of o2: " + o2.getEncoding());

     // Closes the FileWriter
     o1.close();
     o2.close();
   }
FileWriter writes streams of characters while FileOutputStream is meant for writing streams of raw bytes.
FileWriter deals with the character of 16 bits while on the other hand, FileOutputStream deals with 8-bit bytes.
FileWriter handles Unicode strings while FileOutputStream writes bytes to a file and it does not accept characters or strings and therefore for accepting strings, it needs to be wrapped up with OutputStreamWriter.
Method                                         
Method                                                      
nishkarshgandhi
Java-IO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Comparator Interface in Java with Examples
HashMap get() Method in Java
Introduction to Java
Difference between Abstract Class and Interface in Java