Java FileWriter Class

Category: Java   Tags: Java, Java File Handling, Java Character Stream, Java Writer Class, Java FileWriter Class

The FileWriter class creates a Writer and used to write the characters to a file. It has below declaration:

                                    public class FileWriter
                                    extends OutputStreamWriter
                                

Constructors

public FileWriter(String fileName) throws IOException
Create a FileWriter object with given file name.
public FileWriter(File file) throws IOException
Create a FileWriter object with given file object.
public FileWriter(String fileName, boolean append) throws IOException
Create a FileWriter object with given file name. If append is true, then data will be written to the end of the file rather than the beginning.
public FileWriter(File file, boolean append) throws IOException
Create a FileWriter object with given file object. If append is true, then bytes will be written to the end of the file rather than the beginning.
public FileWriter(FileDescriptor fd) throws FileNotFoundException
Creates a new FileWriter by using the file descriptor fd, which represents an existing connection to an actual file in the file system.

Methods

It inherit methods from Writer class.

Here is a simple Java program for FileWriter. This program will write the string to the file:

FileWriterExample.java

                            package com.tutorial.java.files;

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

                            public class FileWriterExample {

                                public static void main(String[] args) throws IOException {
                                    FileWriter writer = null;
                                    String str = "Write me off to the file.";
                                    try {
                                        writer = new FileWriter("/home/manish/sample.txt");
                                        writer.write(str);
                                    } finally {
                                        if(writer != null)
                                            writer.close();
                                    }

                                }
                            }