How to Append Data to Text File in Java

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.
  1. import java.io.*;
3. In your main, initialize a text file named "data.txt".
  1. File file = new File("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.
  1. try
  2. {
  3. FileWriter writer = new FileWriter(file, true);
  4. writer.write("Sourcecodester is the best!"
  5. + System.getProperty("line.separator"));
  6. writer.flush();
  7. writer.close();
  8. }
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.
  1. catch (IOException e)
  2. {
  3. e.printStackTrace();
  4. }
Output: output Here's the full code of this tutorial:
  1. import java.io.*;
  2. public class AppendData
  3. {
  4. public static void main(String[] args)
  5. {
  6. File file = new File("data.txt");
  7.  
  8. try
  9. {
  10. FileWriter writer = new FileWriter(file, true);
  11. writer.write("Sourcecodester is the best!"
  12. + System.getProperty("line.separator"));
  13. writer.flush();
  14. writer.close();
  15. } catch (IOException e)
  16. {
  17. e.printStackTrace();
  18. }
  19. }
  20. }
  21.  
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

Add new comment