Java file writing in is an easy task because java provides a rich set of of API in accomplishing the task at hand. In this tutorial we will be showing you an example source code that will be useful in your everyday programming. We will be using class FileWriter and wrapped it with BufferedWriter class.

Java File Writing using BufferedWriter

package com.javatutorialhq.tutorial;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class FileWriteBuffer {
	/**
	 * This java sample code shows how to write file
	 * Property of javatutorialhq.com
	 * All Rights Reserved
	 * Version 1.0
	 * 04/21/2012
	 */
	public static void main(String[] args) {
		File fileInput = new File("C:\\temp\\testWrite.txt");
		FileWriter fileWriter;
		try {
			fileWriter = new FileWriter(fileInput);
			BufferedWriter bufferWrite = new BufferedWriter(fileWriter);
			bufferWrite.append("TestLine1");
			bufferWrite.append("TestLine2");
			bufferWrite.flush();
			bufferWrite.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

File writing in java requires usage of File class, a writer class, and then a wrapper class. File class  accepts string filename as parameter on its constructor which in turn used as an input for FileWriter class that takes File object as an input. Wrapper class BufferedWriter takes a Writer object which in this case, a FileWriter class. BufferedWriter exposes method that would enable us to write characters into a file in java

From the example above, notice the bufferWrtiter.flush() method invocation of java wrapper class BufferedWriter. This is necessary to finalize the writing of characters to your file. Without this characters that you intend to write would not be present on the file.

There is also one interesting method that you could use the newLine(). We could use this in appending a new line character to our series of characters that we intend to write on a file using java.