Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Java FileWriter Class

In this tutorial, we will learn about FileWriter class in Java. This class is used to write the data inside the file. This class extends OutputStreamWriter. This class provides methods to write strings directly so we don't need to convert string to a byte array.

Constructors of FileWriter Class

This class comes with two variants of constructors that are given below.

Constructor Description
FileWriter(String file) This constructor creates a new file. It gets the file name in a string.
FileWriter(File file) This constructor creates a new file. It gets the file name in the File object.

Methods of FileWriter Class

All the methods supported by FileWrite Class are mentioned in the table below.

Method Description
void write(String text) This method is used to write the string into FileWriter.
void write(char c) This method is used to write the char into FileWriter.
void write(char[] c) Thi method is used to write char array into FileWriter.
void flush() This method is used to flushes the data of FileWriter.
void close() This method is used to close the FileWriter.

Example

In the example given below, we are writing data into the file using FileWriter. Firstly we create an object of FileWriter class then we write data using the read() method.

package studytonight;
import java.io.FileWriter;
public class StudyTonight 
{
	public static void main(String args[])
	{
		try{   		
			FileWriter filewriter=new FileWriter("E:\\studytonight\\output.txt");    
			filewriter.write("Welcome to Studytonight");    
			filewriter.close(); 
			System.out.print("Data Written to the file successfully...");
		}
		catch(Exception e){
			System.out.println("Error: "+e.toString());
		}
	}
}


Data Written to the file successfully...

output.txt

Welcome to Studytonight

Example of getEncoding() method in FileWriter class

In the following example, we are using getEncoding() method to check the character encoding. We can see in the output of this example we are getting UTF8 as a character encoding of this FileWriter. If we do not specify in that case it will display default encoding.

package studytonight;
import java.io.FileWriter;
import java.nio.charset.Charset;
public class StudyTonight 
{
	public static void main(String args[])
	{
		try
		{   		
			FileWriter filewriter=new FileWriter("E:\\studytonight\\output.txt",Charset.forName("UTF8"));        
			//getting encoding of filewriter
			System.out.println("Character Encoding of filewriter is: "+filewriter.getEncoding());
			filewriter.close(); 
		}
		catch(Exception e)
		{
			System.out.println("Error: "+e.toString());
		}
	}
}


Character Encoding of filewriter is: UTF8

Conclusion:

In this tutorial, we learned about FileWriter class in Java. This class belongs to the java.io package and it is used to write data in the files. We also learned out to get the type of encoding that is used for writing the data.