Java – StringBuffer class and Chinese character encoding

I wrote a method to return a string containing Chinese characters

public printChineseMenu(){
   StringBuffer buffer;
   buffer.append(chinese string returned from DB);     //chinese characters appear in sql
   System.out.println(buffer);                         //they appear as question marks
   PrintStream out = new PrintStream(System.out,true,"UTF-8");
   out.println(buffer);                                //chinese characters appear

   return (buffer.toString())
}

Is there a better type to store / return Chinese strings than the StringBuffer class

Solution

The problem here is not StringBuffer - it's just system Out the code used When printing strings directly without using StringBuffer, you will find exactly the same behavior

StringBuffer (and its more modern, non thread safe equivalent, StringBuilder, you should use it) doesn't care about coding itself - they only use utf-16 code unit sequences They will retain all Unicode data correctly So is string

Your method almost certainly returns only one string - but if you don't need to do any "building" with strings (attach other parts), there's no point using StringBuffer or StringBuilder If you really need to build a reslut string from multiple strings, you can use any of them and return only the results of toString () you are already doing (although the parentheses around the return value are irrelevant; return is not a method)

In terms of string data, the console is usually misleading If in doubt, print the UTF - 16 code unit sequence one at a time and find out its meaning In this way, there is no danger that encoded or non printable characters will become a problem

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>