Monday, September 2, 2024

How to append text to file in Java? Example Tutorial

Hello guys, In this article, I'll teach you how to append text to a file in Java. Earlier, I have taught you guys how to create a file and write text into it, but, append is totally different than creating a new file and writing data into it. In the case of append, the file already exists and you just add text at the end of the file. One popular example of appending text into a file is a log file that is constantly updated because your application continuously appends log details into it. While you don't need to create a logging framework here, just knowing how to append text into an existing file in Java is useful for Java programmers of all kinds of experience.


Here is how the file looked like before and after executing this Java program.

Before:
Top 5 Technology Companies in World
Apple
Google
Amazon
Microsoft
Cisco

After (without append) :
Without append, your content will be overwritten just like below :
Facebook
Twitter

After (with append) :
Top 5 Technology Companies in World
Apple
Google
Amazon
Microsoft
Cisco
Facebook
Twitter






How to append text to a file in Java? Example

Convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.

Whether or not a file is available or may be created depends upon the underlying platform. Some platforms, in particular, allow a file to be opened for writing by only one FileWriter (or other file-writing objects) at a time. In such situations, the constructors in this class will fail if the file involved is already open.

FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream. If you want to learn more about Java IO API, I suggest you pick a comprehensive Java course like these best Java Programming courses which contains the best Java courses from Udmey, Coursera, Pluralsight, and other popular websites. 

How to append text to file in Java



Error:
Exception in thread "main" java.lang.NullPointerException
               at java.io.Writer.<init>(Writer.java:88)
               at java.io.BufferedWriter.<init>(BufferedWriter.java:101)
               at java.io.BufferedWriter.<init>(BufferedWriter.java:88)
               at Testing.main(Testing.java:18)


Code :
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
/**
 * Java Program to append text to file.
 * @author
 */
public class JavaFileAppendExample {
    public static void main(String args[]) {
        FileWriter fw = null;
        BufferedWriter bfw = null;
        try {
            //fw = new FileWriter("data.txt"); //This will overwrite 
                                               // existing file
            fw = new FileWriter("data.txt", true);
            bfw = new BufferedWriter(fw);

            bfw.write("Facebook");
            bfw.write("Twitter");
            bfw.flush();
            System.out.println("Successfully, text appended to file");
        } catch (IOException failure) {
            // handle error
        } finally {
            // close files and streams
            try {
                if (fw != null) {
                    fw.close();
                }
            } catch (IOException failed) { /* can't do anything */ }
            try {
                if (bfw != null) {
                    bfw.close();
               }
            } catch (IOException failed) { /* can't do anything */ }

        }
    }
}

Output:
System.out.println("text appended to file");

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

/**
*
* @author
*/
public class Testing {
    public static void main(String args[]) {
        try (FileWriter fw = new FileWriter("data.txt", true);
             BufferedWriter bfw = new BufferedWriter(fw);) {
            bfw.write("\nFacebook");
            bfw.write("\nTwitter");

            bfw.flush();
            System.out.println("text appended to file");
        } catch (IOException failure) {
            // handle error
        }
    }
}


Output:
text appended to file

File after execution:
Top 5 Technology Companies in World
Apple
Google
Amazon
Microsoft
Cisco
Facebook
Twitter


In Java 7, by using try-with-resources statements for automatic resource cleanup, this code will be much shorter.

Other Java tutorials for Java programmers
  • How to convert JSON array to String array in Java using Gson? (tutorial)
  • 6 Courses to learn Spring in depth (courses)
  • How to Escape JSON String in Eclipse (tips)
  • How to ignore Unknown properties while parsing JSON in Java? (tutorial)
  • 3 ways to convert String to JSON object in Java? (tutorial)
  • 5 JSON libraries Java JEE Programmer should know (list)
  • Why use Spring to create REST API in Java? (article)
  • How to parse JSON with the date field in Java using Jackson? (tutorial)
  • How to download the Jackson library for JSON parsing? (tutorial)
  • How to convert a JSON Array to String Array in Java? (tutorial)
  • How to parse a large JSON file using Jackson Streaming API? (example)
  • How to use Google Protocol Buffer (protobuf) in Java? (tutorial)
  • Top 5 courses to learn Spring boot in-depth (courses)
  • Top 10 RESTful Web Service Interview Questions (see here)
  • What is the purpose of different HTTP methods in REST? (see here)
  • 5 Courses to learn RESTFul Web Services in Java? (courses)

Thanks for reading this article so far. If you like this Jackson tutorial to parse CSV file in Java then please share with your friends and colleagues. If you have any questions or feedback then please drop a note. 


P. S. - If you are new to Java and looking for some free courses to start with then you can also check out this list of free Java Courses for Beginners. Join them before they expire.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.