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



Home Java Examples Io Java File Writing Example

Related Tutorials


 
 

Share on Google+Share on Google+

Java File Writing Example

Advertisement
To write some data on the file you need to first open the file in append mode by using the java.io.FileWriter class and then pass the fileWriter object to the BufferedReader constructor. and write some data using bufferedWriter object and finally close it.

Java File Writing Example

To write some data on the file you need to first open the file in append mode by using the java.io.FileWriter class and then pass the fileWriter object to the BufferedReader constructor. and write some data using bufferedWriter object and finally close it.

FileWriter fileWriter = new FileWriter("sampleFile.txt", true);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("Adding New Information to the File");
bufferedWriter.close();

A Sample example is given below that inputs the file name from the user, When file exists, then it opens, and take the file data that have to be written on the file, as input.

SampleInterfaceImp.java

import java.io.*;
public class JavaFileExample{
	public static void main(String args[]){
	  try{
		
		  System.out.println("Please Enter File Name and its location as roseindia/file.txt");
		  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		  String fileName=br.readLine();

		  FileWriter fileWriter = new FileWriter(fileName, true);
		  BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

		  System.out.println("Please Enter File Data");

		  BufferedReader bufferedData=new BufferedReader(new InputStreamReader(System.in));
		  String dataToWriteOnFile=bufferedData.readLine();

		  bufferedWriter.write(dataToWriteOnFile);

		  bufferedWriter.close();
		  
	  }catch (Exception e){
		System.err.println("Error: " + e.getMessage());
	  }  
	}
}

Note:- Before running this example you must create a text file that you have to append (for example file.txt)

When you will run the example you will get the following output as


F:\Core Java Examples>java JavaFileExample
Please Enter File Name and its location as roseindia/file.txt
file.txt
Please Enter File Data
Hi Friends

Download Select Source Code

Advertisement

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

Related Tutorials

Discuss: Java File Writing Example  

Post your Comment


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