Java Write to File

In this tutorial you will learn how to write to file in java.

Java Write to File

In this tutorial you will learn how to write to file in java.

Java Write to File

Java Write to File

In this tutorial you will learn how to write to file in java.

Write to a file in java we are required to use some classes of java.io package. Here in this example I have used the classes FileWriter and BufferedWriter.

FileWriter : This class writes the streams of characters. It is convenient in writing a character files.

BufferedWriter : This class stores the characters in a buffer to write into a character-output stream. Buffering feature of this class makes it efficient for writing of single characters, arrays and strings. For the convenience generally this class should be wrapped around any Writer because, some Writer's write() method's operations may take more time to write. These Writer can be FileWriter, OutputStreamWriter etc.

Example :

WriteToFileExample.java

import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
class WriteToFileExample 
{
public static void main(String args[])
{
BufferedWriter br= null;
try
{
File file = new File("fileWriter.txt");
FileWriter fw = new FileWriter(file);
/* You can also give the path as C:\\Desktop\\fileWriter.txt */
BufferedWriter br = new BufferedWriter(fw);
br.write("This example demonstrates you how to write in a file.");
br.close();
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
}

How to Execute this example :

After doing the basic process to execute a java program write simply on command prompt as :

javac WriteToFileExample.java to compile the program

And after successfully compilation to run simply type as :

java WriteToFileExample

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 programmatically. like as :

Download Source Code