In this example you will learn how to write to file using FileWriter.
Writing to a file there is a class in java.io package named FileWriter. Object of this class can be created using the following of its constructor :
In the Example I have created an object of file using the class File of java.io package and also creates a FileWriter object using the FileWriter(File file) constructor and passed the file object to its instance. Then using its write() method writes streams of character to file.
Example :
WriteTofileFileWriter.java
import java.io.File;
import java.io.FileWriter;
class WriteTofileFileWriter
{
public static void main(String args[])
{
String str = "This example demonstrates you how to write to file using FileWriter";
File file = null;
FileWriter fw = null;
try
{
file = new File("writeTofileFileWriter.txt");
fw = new FileWriter(file);
fw.write(str);
fw.close();
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("File is created and contents are written into successfully");
}
}
How to Execute this example :
After doing the basic process to execute a java program write simply on command prompt as :
javac WriteTofileFileWriter.java to compile the program
And after successfully compilation to run simply type as :
java WriteTofileFileWriter
Output :
When you will execute this example a text file will be created on the specified place as the path given by you with containing the text that you are trying to write in that file by java program like as :

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: Java Write To File FileWriter
Post your Comment