Home Java Examples Io Java File Writing Example



Java File Writing Example
Posted on: January 18, 2012 at 12:00 AM
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

Related Tags for Java File Writing Example:


More Tutorials from this section

Ask Questions?    Discuss: Java File Writing Example  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.