将字符串编码为 UTF-8 [英] Encode String to UTF-8

查看:42
本文介绍了将字符串编码为 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆