File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 EJB 3 in Action this week in the EJB and other Java EE Technologies 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: 1937
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.
I agree. Here's the link:
subject: Appending text to file in UTF-8
Similar Threads
printing multiple output
write to f file
Alignment is working only sometimes in editor made in java.
Deleting contents from a file
Need help writing a text file