Java Filewriter Class

The Java FileWriter class is utilized for writing character-based information to a file. It belongs to the character-oriented category of classes that manage file operations in Java.

In contrast to the FileOutputStream class, there is no requirement to manually convert a string into a byte array when using this alternative class. This class furnishes a method that allows for direct writing of strings without the need for prior conversion.

Java FileWriter class declaration

Let's examine the syntax for the Java.io.FileWriter class declaration:

Example

public class FileWriter extends OutputStreamWriter

Constructors of FileWriter class

Constructor Description
FileWriter(String file) Creates a new file. It gets file name instring.
FileWriter(File file) Creates a new file. It gets file name in Fileobject.

Methods of FileWriter class

Method Description
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.

Java FileWriter Example

In this instance, we are utilizing the Java FileWriter class to write data into the file named testout.txt.

Example

package com.example;

import java.io.FileWriter;

public class FileWriterExample {

	public static void main(String args[]){  

		 try{  

		   FileWriter fw=new FileWriter("D:\\testout.txt");  

		   fw.write("Welcome to Java.");  

		   fw.close();  

		  }catch(Exception e){System.out.println(e);}  

		  System.out.println("Success...");  

	 }  

}

Output:

Output

Success...

testout.txt:

Example

Welcome to Java.

Input Required

This code uses input(). Please provide values below: