Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Appending text to file in UTF-8

 
Jiri Nejedly
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2969
59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Many thanks.
Just adding the append parameter to FileOutputStream and everything works.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic