在Android中,将字符串转换为UTF-8编码,可以使用以下方法:
1. 使用`String`类的`getBytes(Charset charset)`方法:
```java
String str = "你好,世界!";
byte[] utf8Bytes = str.getBytes(StandardCharsets.UTF_8);
```
2. 使用Apache Commons库中的`StringUtils`类:
首先,需要在项目的`build.gradle`文件中添加依赖:
```groovy
implementation 'org.apache.commons:commons-lang3:3.12.0'
```
然后,使用`StringUtils`类的`toUtf8Bytes`方法:
```java
import org.apache.commons.lang3.StringUtils;
String str = "你好,世界!";
byte[] utf8Bytes = StringUtils.toUtf8Bytes(str);
```