FileWriter creates a Writer that you can use characters to write to a file. Its most commonly used constructors are shown here:

FileWriter(String filePath)
filePath is the full path name of a file
FileWriter(String filePath, boolean append)
If append is true, then output is appended to the end of the file.
FileWriter(File fileObj)
fileObj is a File object that describes the file.
FileWriter(File fileObj, boolean append)
If append is true, then output is appended to the end of the file.

FileWriter will create a file before opening it if the file does not exist. Attempt to open a read-only file results an IOException.

Methods inherited from class

void close() Closes the stream, flushing it first. void flush() Flushes the stream. String getEncoding() Returns the name of the character encoding being used by this stream. void write(char[] cbuf, int off, int len) Writes a portion of an array of characters. void write(int c) Writes a single character. void write(String str, int off, int len) Writes a portion of a string.

Revised from Open JDK source code


public class Main {
  public static void main(String args[]) throws Exception {
    FileWriter fw = new FileWriter(args[0]);
    for (int i = 0; i < 12; i++) {
      fw.write("Line " + i + " \n");

The following create a FileWriter to write to LPT1.


public class MainClass {
  public static void main(String[] args) {
    try {
      FileWriter fw = new FileWriter("LPT1:");

      PrintWriter pw = new PrintWriter(fw);
      String s = "";

      int i, len = s.length();

      for (i = 0; len > 80; i += 80) {
        pw.print(s.substring(i, i + 80));
        len -= 80;

      if (len > 0) {

    } catch (IOException e) {
  Java Book 
    File Stream  

  1. FileWriter
  2. new FileWriter(File file)
  3. new FileWriter(String string)
  4. new FileWriter(String fileName, boolean append)
  5. FileWriter: close()
  6. FileWriter: flush()
  7. FileWriter: write(int i)