用Java将字符串编码为UTF-8

Encode a String to UTF-8 in Java

1.概述

在用Java处理字符串时,有时我们需要将它们编码为特定的字符集。

本教程是一本实用指南,显示了将字符串编码为UTF-8字符集的不同方法。有关更深入的技术知识,请参见我们的字符编码指南。

2.定义问题

为了展示Java编码,我们将使用德语字符串" Entwickeln Sie mitVergnügen"。

1
2
3
4
5
6
String germanString ="Entwickeln Sie mit Vergnügen";
byte[] germanBytes = germanString.getBytes();

String asciiEncodedString = new String(germanBytes, StandardCharsets.US_ASCII);

assertNotEquals(asciiEncodedString, germanString);

使用US_ASCII编码的此String在打印时为我们提供了值" Entwickeln Sie mit Vergn?gen",因为它不理解非ASCIIü字符。但是,当我们将使用所有英文字符的ASCII编码字符串转换为UTF-8时,会得到相同的字符串。

1
2
3
4
5
6
String englishString ="Develop with pleasure";
byte[] englishBytes = englishString.getBytes();

String asciiEncondedEnglishString = new String(englishBytes, StandardCharsets.US_ASCII);

assertEquals(asciiEncondedEnglishString, englishString);

让我们看看使用UTF-8编码时会发生什么。

3.使用Core Java编码

让我们从核心库开始。

字符串在Java中是不可变的,这意味着我们无法更改字符串字符编码。要实现所需的功能,我们需要复制字符串的字节,然后使用所需的编码创建一个新的字节。

首先,我们获取字符串字节,然后,使用检索到的字节和所需的字符集创建一个新的字节:

1
2
3
4
5
6
String rawString ="Entwickeln Sie mit Vergnügen";
byte[] bytes = rawString.getBytes(StandardCharsets.UTF_8);

String utf8EncodedString = new String(bytes, StandardCharsets.UTF_8);

assertEquals(rawString, utf8EncodedString);

4.使用Java 7 StandardCharsets编码

另外,我们可以使用Java 7中引入的StandardCharsets类对String进行编码。

首先,我们将String解码为字节,然后将String编码为UTF-8:

1
2
3
4
5
6
String rawString ="Entwickeln Sie mit Vergnügen";
ByteBuffer buffer = StandardCharsets.UTF_8.encode(rawString);

String utf8EncodedString = StandardCharsets.UTF_8.decode(buffer).toString();

assertEquals(rawString, utf8EncodedString);

5.使用Commons Codec编码

除了使用核心Java外,我们还可以使用Apache Commons Codec获得相同的结果。

Apache Commons Codec是一个方便的软件包,其中包含各种格式的简单编码器和解码器。

首先,让我们从项目配置开始。使用Maven时,我们必须将commons-codec依赖项添加到pom.xml中:

1
2
3
4
5
<dependency>
    <groupId>commons-codec</groupId>
    commons-codec</artifactId>
    <version>1.14</version>
</dependency>

然后,在我们的例子中,最有趣的类是StringUtils,它提供了编码String的方法。使用此类,获取UTF-8编码的String非常简单:

1
2
3
4
5
6
String rawString ="Entwickeln Sie mit Vergnügen";
byte[] bytes = StringUtils.getBytesUtf8(rawString);
 
String utf8EncodedString = StringUtils.newStringUtf8(bytes);

assertEquals(rawString, utf8EncodedString);

六,结论

将字符串编码为UTF-8并不困难,但并不是那么直观。本教程介绍了使用核心Java或使用Apache Commons Codec的三种方式。

与往常一样,可以在GitHub上找到代码示例。