How to write to a file in Java
Use the FileWriter to class to write to a file in Java. FileWriter is a Character Stream class. This class resides in the java.io package and can be used by importing java.io.FileWriter.
Syntax
- First, you have to create a FileWriter instance. This class has multiple constructors:
FileWriter(File file)
FileWriter(File file, boolean append)
FileWriter(FileDescriptor fd)
FileWriter(String fileName)
FileWriter(String fileName, boolean append)
If boolean append is true, the data is written to the end of the file instead of the beginning.
- After creating the instance, you can write to the file using the
FileWriter.write()method.
Example code
import java.io.*;public class FileWriterExample {public static void main(String args[]){try {FileWriter fw=new FileWriter("output/writerTest.txt");fw.write("Educative!");fw.close();}catch(Exception e) {System.out.println(e);}System.out.println("Successfully Written to File!");}}
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved