Java – How to append content to file

In Java, you can use FileWriter(file,true) to append new content to the end of a file.

1. All existing content will be overridden.


new FileWriter(file);

2. Keep the existing content and append the new content to the end of a file.


new FileWriter(file,true);

FileWriter – Append file example

A text file with the following content:

E:\\test\\filename.txt

ABC Hello

Java example to append new content to the end of a file.

AppendToFileExample.java

package com.mkyong;

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

public class AppendToFileExample {

	private static final String FILENAME = "E:\\test\\filename.txt";

	public static void main(String[] args) {

		BufferedWriter bw = null;
		FileWriter fw = null;

		try {

			String data = " This is new content";

			File file = new File(FILENAME);

			// if file doesnt exists, then create it
			if (!file.exists()) {
				file.createNewFile();
			}

			// true = append file
			fw = new FileWriter(file.getAbsoluteFile(), true);
			bw = new BufferedWriter(fw);

			bw.write(data);

			System.out.println("Done");

		} catch (IOException e) {

			e.printStackTrace();

		} finally {

			try {

				if (bw != null)
					bw.close();

				if (fw != null)
					fw.close();

			} catch (IOException ex) {

				ex.printStackTrace();

			}
		}

	}

}

Output: The new content is appended to the end of the file.

E:\\test\\filename.txt

ABC Hello This is new content

Reference

  1. FileWriter JavaDoc
  2. BufferedWriter JavaDoc
  3. How to write to file in Java – BufferedWriter

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
16 Comment threads
12 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
27 Comment authors
JyotiadfgadfgaividyfymkyongRoopam Gupta Recent comment authors
newest oldest most voted
akungery
Guest
akungery

how if i want to write that String data on specific line?
e.g.
bufferWritter.writeLine(4);
bufferWritter.write(data);
bufferWritter.close();
how to do something like that?

Jyoti
Guest
Jyoti

i need to append text from the jtextfield to a specific key of a file..how to do this?

adfgadfga
Guest
adfgadfga

you can append the text to new line each time, instead of end of the file, by adding:
bw = new BufferedWriter(fw); [original code]
bw.newLine(); [new code]
bw.write(data); [original code]

Roopam Gupta
Guest
Roopam Gupta

FileWriter fw=new FileWriter(file,true);
You are using file.getName Because of which it was not working Plz modify your code so the learner doesn’t get problem to understand…

mkyong
Guest
mkyong

Article is updated, thanks.

ron
Guest
ron

How do you do this with Android ?

Amitabh Roy
Guest
Amitabh Roy

FileWriter fileWritter = new FileWriter(file.getName(),true); should be replaced by
FileWriter fileWritter = new FileWriter(file.getAbsoluteFile(),true);

mkyong
Guest
mkyong

Fixed, thanks.

Ye ChaoHui
Guest
Ye ChaoHui

//if file doesnt exists, then create it
if(!file.exists()){
file.createNewFile();
}

if not do this and file not exist, will create a file himself?

Kraeuterbutter8
Guest
Kraeuterbutter8

No, i’ve tested it, and as it seems, it won’t create it until you call “file.createNewFile();”

Valium
Guest
Valium

Your own report offers established beneficial to me personally.

It_s quite informative and you’re obviously very well-informed in this region. You possess opened my personal face for you to different views on this particular matter with intriguing and strong content material.

krish
Guest
krish

the below code not working for me untill I changed the following line:
FileWriter fileWritter = new FileWriter(file.getName(),true);

to this:

FileWriter fileWritter = new FileWriter(file,true);

Mkyong please modife the code

Mohammed Rukhsar
Guest
Mohammed Rukhsar

In place of file.getName(),u use file.getPath() and after that u must pass that value.
So it will be work.

Zenith
Guest
Zenith

Gr8!! That worked!! Thank you :)

NISHIT PATIRA
Guest
NISHIT PATIRA

file.getName() gives only the name of the file and not the entire path, hence when the object is being made, it is not going to know, in which directory to search for the file.

file.getPath() gives the entire path.

krishna
Guest
krishna

Thanks for alerting me to that. Now Come on mykong either sort this code out or delete it !

Dave
Guest
Dave

Hi, Thanks for the code snippet, it’s useful. It’s probably a good idea to wrap the bufferWritter.close(); in a finally block in case of any exceptions before then. This will prevent unclosed filehandles on the FS.

A.J
Guest
A.J

Hi

thanks for this code it truly saved me a lot of time and headache tablets loll

Kind Regards
A.J Bosch

Divyasree
Guest
Divyasree

haii friends,
Here why we have to pass the FileWriter variable to the BufferedWriter as argument??

Faisal
Guest
Faisal

Don’t know why the given “Append file example” was not working for me untill I changed the following line:

FileWriter fileWritter = new FileWriter(file.getName(),true);

to this:

FileWriter fileWritter = new FileWriter(file,true);
Nitesh Rajput
Guest
Nitesh Rajput
<p> Same thing happening with me also,when i tried to append contents to existing file <br> by using 
FileWriter fileWritter = new FileWriter(file.getName(),true) <br> it was not appending and also not giving any exception,but when i changed this with FileWriter fileWritter = new FileWriter(file,true); <br>
Its running fine and giving actual result.

dannerman
Guest
dannerman

Yes damn it’s true!!!
thank you for your reply, I got stuck in file.getName() !!!! :-(

jegadees
Guest
jegadees

yes, this has happened in my case too. anyway thank you mkyong

TanViet
Guest
TanViet

@Faisal: I have also same problem. Thank you!

Devi
Guest
Devi

is it possible to concatenate two audio files in android?.please reply
if any one knows solution for this.

Jerry
Guest
Jerry

I know this forum is old, so I hope you still can respond. This code works for me, except it writes the file to the current directory. I am trying to write the file to a specified directory. below is my code: The behavior of the code is as follows: 1) The code creates a new directory(X) 2) The code creates a new file(F) in that directory(X) – it is empty file 3) The code creates another file(F2) in the current directory(X2) 4) The code writes and appends data to the file(F2) in the current directory(X2) 5) The file(F) created… Read more »

sibani dash
Guest
sibani dash

My file contains } at the end.how can i add it before last closing curly brace instead of appending at the end of the file.

ividyfy
Guest
ividyfy

Szybkie po?yczki bez biku i krd