How to Append Data to Text File in Java
Submitted by donbermoy on Wednesday, May 14, 2014 - 09:18.
In this tutorial, i will teach you how to append data to a text file using Java. I already had tutorial in creating a file, and now, we will put a data to this file.
So, now let's start this tutorial!
1. Open JCreator or NetBeans and make a java program with a file name of AppendData.java.
2. Import java.io package. Hence we will use an input/output in creating files.
3. In your main, initialize a text file named "data.txt".
4. Now, create a try and catch method. In your try method, do the following code. This will trigger to create files and will append/write data to our text file.
line.separator syntax is for having a new line. The flush method in our writer variable as FileWriter, flushes the output stream and forces any buffered output bytes to be written out. Then, we close the writer or the file that we have created that has now a data on it. This will write a text on the data.txt text file as "Sourcecodester is the best!".
In your Catch method, prefer to catch IOException then use printStackTrace() method. This will help to trace the exception and identify which method causes the bug.
Output:
Here's the full code of this tutorial:
Hope this helps! :)
Best Regards,
Engr. Lyndon R. Bermoy
IT Instructor/System Developer/Android Developer/Freelance Programmer
If you have some queries, feel free to contact the number or e-mail below.
Mobile: 09488225971
Landline: 826-9296
E-mail:[email protected]
Add and Follow me on Facebook: https://www.facebook.com/donzzsky
Visit and like my page on Facebook at: https://www.facebook.com/BermzISware
- import java.io.*;
- try
- {
- writer.write("Sourcecodester is the best!"
- writer.flush();
- writer.close();
- }
- {
- e.printStackTrace();
- }

- import java.io.*;
- public class AppendData
- {
- {
- try
- {
- writer.write("Sourcecodester is the best!"
- writer.flush();
- writer.close();
- {
- e.printStackTrace();
- }
- }
- }
Add new comment
- 53 views