FileWriter Class in Java

FileWriter creates a Writer that you can use to write to a file. FileWriter is convenience class for writing character files. 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 Constructors

  • FileWriter(File file) - Constructs a FileWriter object given a File object.
  • FileWriter(File file, boolean append) - Constructs a FileWriter object given a File object.
  • FileWriter(FileDescriptor fd) - Constructs a FileWriter object associated with a file descriptor.
  • FileWriter(String fileName) - Constructs a FileWriter object given a file name.
  • FileWriter(String fileName, boolean append) - Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.

FileWriter class Methods

  • void write(String text) - It is used to write the string into FileWriter.
  • void write(char c) - It is used to write the char into FileWriter.
  • void write(char[] c) - It is used to write char array into FileWriter.
  • void flush() - It is used to flushes the data of FileWriter.
  • void close() - It is used to close the FileWriter.

FileWriter class Example

FileWriter is meant for writing streams of characters so provide input for below program is character string like:
String content = "This is the text content";
This program writes character streams to file "sample.txt" file. This example uses the try-with-resources statement to close the resources automatically.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * The class demonstrate the usage of FileWriter class methods.
 * @author javaguides.net
 *
 */

public class FileWritterExample {
 public static void main(String[] args) {
  File file = new File("sample.txt");
  String content = "This is the text content";

  try (FileWriter fop = new FileWriter(file)) {

   // if file doesn't exists, then create it
   if (!file.exists()) {
    file.createNewFile();
   }
   fop.write(content);

  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

Reference

Comments