Home Java Examples Io Java Write to File
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

Java Write to File

Advertisement
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.

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

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: January 17, 2012

Related Tutorials

Ask Questions?    Discuss: Java Write to File  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com