将字符串编码为 UTF-8 [英] Encode String to UTF-8
问题描述
我有一个带有ñ"字符的字符串,但我遇到了一些问题.我需要将此字符串编码为 UTF-8 编码.我已经用这种方法试过了,还是不行:
I have a String with a "ñ" character and I have some problems with it. I need to encode this String to UTF-8 encoding. I have tried it by this way, but it doesn't work:
byte ptext[] = myString.getBytes();
String value = new String(ptext, "UTF-8");
如何将该字符串编码为 utf-8?
How do I encode that string to utf-8?
推荐答案
String
Java 中的对象使用无法修改的 UTF-16 编码.
String
objects in Java use the UTF-16 encoding that can't be modified.
唯一可以有不同编码的是byte[]
.因此,如果您需要 UTF-8 数据,那么您需要一个 byte[]
.如果您有一个包含意外数据的 String
,那么问题出在更早的地方,错误地将一些二进制数据转换为 String
(即它使用了错误的编码).
The only thing that can have a different encoding is a byte[]
. So if you need UTF-8 data, then you need a byte[]
. If you have a String
that contains unexpected data, then the problem is at some earlier place that incorrectly converted some binary data to a String
(i.e. it was using the wrong encoding).
这篇关于将字符串编码为 UTF-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!