Search

Wednesday, July 1, 2015

How to append text to existing File in Java? Example

In last tutorial, you have learned about how to write data to a file in Java and in this tutorial you will learn how to append text to a file in Java. What is difference between simply writing to a file vs appending data to a file? In case of writing to a file, program can start writing from start but in case of appending text, you start writing from the end of the file. You can append text into an existing file in Java by opening a file using FileWriter class in append mode. You can do this by using special constructor provided by FileWriter class, which accepts a file and a boolean, which if passed as true then open the file in append mode. This means you can write new content at the end of the file. One of the common example of appending text into file is logging but for that you don't need to write your own logger, there are several good logging library available in Java world e.g. Log4j, SLF4j, Logbak and even java.util.logging is good enough. In this tutorial, you will learn how to append data to an existing text file from Java program. As I said previously, if you are starting fresh in Java then I suggest you to better follow a book because they provide comprehensive coverage, which means you can learn lot of things in quick time. You can follow either core Java by Cay S. Horstmann or Java : A Beginners guide by Herbert Schildt, both are very good book and highly recommended for beginners in Java. Good point about a beginner's guide is that it also covers Java 8 while core Java 9th Edition only covers up-to Java 7.
Read more »

No comments:

Post a Comment