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.

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.

Java File Writing Example

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