In this section we will be showing a java source code on how to append string of character lines on an existing file. A practical scenario where in you need to keep a certain record on an existing file.

Append lines to existing file in java

The source code provided leveraged the use of FileWriter class that takes two arguments on its constructor, the first one is File and the second one is a boolean. The boolean parameter indicates true if you want the append functionality which is our primary objective to append strings of characters at the existing file. Since we are after appending a new line with a set of string characters, we would be needing to append a new line character. In this source code we will get it from the system property.

package com.javatutorialhq.tutorial;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class AppendExistingFile {

	/**
	 * This sample code shows
	 * how to append new line of strings or characters to existing file
	 * Property of javatutorialhq.com
	 * All Rights Reserved
	 * Version 1.0
	 * 07/01/2012
	 */

	public static void main(String[] args) {
		File f = new File("C:\\temp\\test.log");
		boolean b;
		if(f.exists()){
			try {
				BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));
				bw.append(System.getProperty("line.separator"));
				bw.append("line 4");
				bw.flush();
				bw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		else{
			System.out.println(f.getAbsolutePath() + " does not exists");
		}
	}

}
[/fusion_builder_column][/fusion_builder_row][/fusion_builder_container]