Meaningless Drivel is fun!*
The moose likes Beginning Java and the fly likes Appending text to file in UTF-8 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Appending text to file in UTF-8" Watch "Appending text to file in UTF-8" New topic

Appending text to file in UTF-8

Jiri Nejedly
Ranch Hand

Joined: Oct 22, 2002
Posts: 81
Hi. I'm appending text to the end of file:

How to modify this code, so the appended text will be in UTF-8 ?

Tony Docherty

Joined: Aug 07, 2007
Posts: 2176
The API docs for FileWriter say "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.". So if your default character is not UTF-8 you can't use FileWriter.

Unfortunately life is not as simple as just using something like the following unless you can guarantee your output text can be encoded as UTF-8:

The problem is this will silently hide encoding errors so if you need to detect these will have to create an encoder ie:

Jiri Nejedly
Ranch Hand

Joined: Oct 22, 2002
Posts: 81
Many thanks.
Just adding the append parameter to FileOutputStream and everything works.
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: Appending text to file in UTF-8
Similar Threads
printing multiple output
Alignment is working only sometimes in editor made in java.
write to f file
Need help writing a text file
Deleting contents from a file