Home Java Examples Io Java Write To File FileWriter

Related Tutorials


 
 

Share on Google+Share on Google+

Java Write To File FileWriter

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

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

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 19, 2012

Related Tutorials

Discuss: Java Write To File FileWriter  

Post your Comment


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