[英]How to convert a sequence of character to UTF-8 in Java?
Sorry for asking basic questions here. 很抱歉在这里提出基本问题。 Pardon me.
对不起。
I have a sequence a string in this in unicode as follows. 我在Unicode中有一个字符串序列,如下所示。
String unicode = "\u8BF7\u5728\u6B64\u5904\u8F93\u5165\u4EA7\u54C1\u7F16\u53F7\u6216\u540D\u79F0";
How can I convert this to Chinese text or the UTF-8 text ? 如何将其转换为中文文本或UTF-8文本?
The String itself will always be in Unicode; 字符串本身将始终使用Unicode; I'm not sure what you mean by "convert this to Chinese text" but to convert it to the binary representation using UTF-8 you'd use:
我不确定“将其转换为中文文本”是什么意思,而是要使用UTF-8将其转换为二进制表示形式:
byte[] bytes = unicode.getBytes("UTF-8");
or you can use the Charset
- using the Guava library for example, you'd just use: 或者您可以使用
Charset
-例如,使用Guava库,您只需使用:
byte[] bytes = unicode.getBytes(Charsets.UTF_8);
(This gets round the brittleness of specifying a string, and avoids worrying about catching UnsupportedEncodingException
.) (这避免了指定字符串的脆弱性,并且避免了担心捕获
UnsupportedEncodingException
。)
Or you can declare: 或者您可以声明:
final static Charset UTF_8 = Charset.forName("UTF-8");
at the top of your class to avoid a whole library as a cure for the string. 避免在整个类库中使用该库来解决字符串问题。
您在上面说过要输出到浏览器吗?...如果您使用的是servlet或类似的方法,则可以采用多种方法,因此您可能需要在问题中更具体一些,因为可以指定unicode / utf http响应标头或html输出中的-8 / utf-16,例如,在<head>
元素内部输出以下标记:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.