I use the following code to save Chinese characters into a .txt file, but when I opened it with Wordpad, I couldn’t read it.
StringBuffer Shanghai_StrBuf = new StringBuffer("\u4E0A\u6D77");
boolean Append = true;
FileOutputStream fos;
fos = new FileOutputStream(FileName, Append);
for (int i = 0;i < Shanghai_StrBuf.length(); i++) {
fos.write(Shanghai_StrBuf.charAt(i));
}
fos.close();
What can I do ? I know if I cut and paste Chinese characters into Wordpad, I can save it into a .txt file. How do I do that in Java ?
There are several factors at work here:
fos = new FileOutputStream(FileName,Append);Here is a method of reliably appending UTF-8 data to a file:
Usage:
Note: if the file already existed and you chose to append and existing data wasn’t UTF-8 encoded, the only thing that code will create is a mess.
Here is the
Closertype used in this code:This code makes a Windows-style best guess about how to read the file based on byte order marks:
Usage:
(System.out uses the default encoding, so whether it prints anything sensible depends on your platform and configuration.)