File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Appending text to file in UTF-8" Watch "Appending text to file in UTF-8" New topic
Author

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 ?

Thanks
Tony Docherty
Bartender

Joined: Aug 07, 2007
Posts: 2289
    
  49
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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Appending text to file in UTF-8