How to update a file in Java?

I’ve been reading books in Java just to find a code on how to update a file just to append a text in it. A lot of code fragments on Java File available but it just give you how to write a file alone, and or how to read a file alone. This article will help you to create at the same time append a text to an existing file.

Here’s a sample of simple and short Java code to create (if not created) and append a file if existing.

public void createOrAppendFile (File f, String text) throws IOException {
 BufferedWriter bw = new BufferedWriter (new FileWriter (File, true));
 bw.write (text);
 bw.newLine();
 bw.flush();
 bw.close();
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s