Java Write To File FileWriter

In this example you will learn how to write to file using FileWriter.

Java Write To File FileWriter

In this example you will learn how to write to file using FileWriter.

Java Write To File FileWriter

Java Write To File FileWriter

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 :

  • FileWriter(File file) : This constructor creates a FileWriter object with the given a File object.
  • FileWriter(File file, boolean append) : This constructor creates a FileWriter object with given a File object that retain the older text if any, when it is trying to write new text in that file.
  • FileWriter(FileDescriptor fd) : This constructor creates a FileWriter object with given FileDescriptor object.
  • FileWriter(String fileName) : This constructor creates a FileWriter object with specified file name.
  • FileWriter(String fileName, boolean append) : This constructor creates a FileWriter object with specified file name that retain the older text if any, when it is trying to write.

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 :

Download Source Code