FileWriter Class in Java

In Java, we can use FileWriter class to write character data to file.

FileWriter Class

The FileWriter class is a part of the java.io package, Which provides classes for performing input and output operations. FileWriter class enables the developers to write character data to a file in a String line manner.

FileWriter Constructor

     FileWriter fw = new FileWriter(String fileName);
     FileWriter fw = new FileWriter(File fileName);

The above FileWriter objects are meant for overriding of existing data. Instead of overriding if we want append operation then we have to create FileWriter object by using following constructor.

     FileWriter fw = new FileWriter(String fileName, boolean append);
     FileWriter fw = new FileWriter(File fileName, boolean append);

Noteā€“ If the specified is unavailable, then all the above FileWriter constructors will create that file.

FileWriter Methods

write( int c )

public void write( int c ) throws IOException

This method is used to write a single character.

write(char[] c)

public void write(     @NotNull  char[] c)
 throws IOException

This method is used to write an array of characters.

write(String str)

public void write(     @NotNull  String str )
throws IOException

This method is used to write the String to the file.

flush()

public void flush()
 throws java.io.IOException

We can use flush() to force data to be written without closing the writer.

close()

public void close()
 throws java.io.IOException

This method is used to close the writer.

Java Program to Write in File

import java.io.FileWriter;

import java.io.IOException;


public class FileWriterClass {
    public static void main(String[] args) throws IOException {
        FileWriter fw = new FileWriter("java.txt");
        fw.write("TheCodeData\n");
        fw.write(65);
        fw.write("\n");
        char [] array = {'j', 'a', 'v', 'a'};
        fw.write(array);
        fw.flush();
        fw.close();

    }
}
Java Program to Write in File

Note- The main problem with FileWriter is we have to insert the line separator (ā€œ\nā€) manually, which varies from system to system. We can solve this problem by using BufferWriter and PrintWriter.

Similar Java Tutorials

Leave a Comment