Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Javatutorial Writing to File in Java

Related Tutorials


 
 

Share on Google+Share on Google+

Writing to File in Java

Advertisement
In this tutorial, you will learn how to write character in a file and how to write text in a file in java language.

Writing to File in Java

Writing any character or text in Java file is possible through using some defined classes such as FileWriter or BufferedWriter in Java programming. The programmers choose the class as per the need as particular class functions particular tasks.

In Java, FileWriter and BufferedWriter are used for writing Character files and Text Files respectively while another class OutputStreamWrite class is used to handle raw byte file.

Class FileWriter

Class FileWriter accedes from the OutputStreamWriter class, used for writing streams of characters. The FileWriter is a class used for writing character files. The FileWriter class has several constructors that can be used according to required objects.

Syntax of class FileWriter:

FileWriter(File file)

This is the simplest example of the class used for writing character file.

BufferedWriter

The BufferWriter class in Java is a character streams class used to write text to a character-output stream. Using this class you can write single character, text, strings, and arrays directly into a file.

Syntex of Class BufferedWriter:

newBufferedWriter(Path, Charset, OpenOption...)

This is the simplest example of the class used for writing text files.

Example:

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());
  }
  }
}
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 7, 2013

Related Tutorials

Discuss: Writing to File in Java  

Post your Comment


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