FileWriter

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 java.io.OutputStreamWriter

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.
ReturnMethodSummary

Revised from Open JDK source code


  import java.io.FileWriter;

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 + " java2s.com \n");
    }
    fw.close();
  }
}
  

The following create a FileWriter to write to LPT1.


import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

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

      PrintWriter pw = new PrintWriter(fw);
      String s = "www.java2s.com";

      int i, len = s.length();

      for (i = 0; len > 80; i += 80) {
        pw.print(s.substring(i, i + 80));
        pw.print("\r\n");
        len -= 80;
      }

      if (len > 0) {
        pw.print(s.substring(i));
        pw.print("\r\n");
      }

      pw.close();
    } catch (IOException e) {
      System.out.println(e);
    }
  }
}
Home 
  Java Book 
    File Stream  

FileWriter:
  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)