Home Java Javatutorial How to Write to a File in Java

Related Tutorials


 
 

Share on Google+Share on Google+

How to Write to a File in Java

Advertisement
In this Java tutorial you will learn How to write to a file in Java through a simple example. To write to a file in Java we will use FileWriter and BufferedWriter classes. After reading this Java tutorial you will be able to use OutputStreamWriter on a FileOutputStream classes to write data to a file from Java program.

In this Java tutorial, we will demonstrate how to write to a file in Java with the help of a sample Java program. After going though this tutorial you will be able to use OutputStreamWriter on a FileOutputStream classes to write data to a file from Java program.

To write the Java Write To File we will use two classes FileWriter and BufferedWriter.

FileWriter

FileWriter is a class, which is used for writing character files. The assumptions of constructors about are that the default character encoding and the default byte-buffer size are acceptable. However, in order to specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.

BufferedWriter

The BufferWriter is a class used to write text to a character-output stream, buffering characters in oreder to provide efficiency to write single characters, arrays, and strings.

import java.io.*;
class FileWrite 
{
 public static void main(String args[])
  {
  try{
  // Create file 
  FileWriter fstream = new FileWriter("out.txt");
  BufferedWriter out = new BufferedWriter(fstream);
  out.write("Hello Java");
  //Close the output stream
  out.close();
  }catch (Exception e){//Catch exception if any
  System.err.println("Error: " + e.getMessage());
  }
  }
}

If you write the program given above and execute it, this will write "Hello Java" into out.txt file. While creating the object of FileWriter class we have passed the name of the file e.g. "out.txt" as constructor argument.

The BufferedWriter class takes FileWriter object as parameter. The write() method of the BufferedWriter class actually writes the data into the text file.

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: October 3, 2013

Related Tutorials

Discuss: How to Write to a File in Java  

Post your Comment


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