java base 加码 解码
时间: 2024-02-25 12:46:45 浏览: 153
Java中的加码和解码指的是将一个字符串或字节数组从一种编码转换为另一种编码的过程。常见的编码包括UTF-8、GBK、ISO-8859-1等。
Java提供了多种方式进行加码和解码操作,包括使用String类的getBytes()方法和构造函数、使用Charset类、使用Base64类等。
使用String类的getBytes()方法和构造函数进行加码和解码操作:
```java
String str = "Hello World";
// 将字符串转换为字节数组,使用默认编码
byte[] bytes = str.getBytes();
// 将字节数组转换为字符串,使用默认编码
String str2 = new String(bytes);
// 将字符串转换为字节数组,指定编码为UTF-8
byte[] bytes2 = str.getBytes("UTF-8");
// 将字节数组转换为字符串,指定编码为UTF-8
String str3 = new String(bytes2, "UTF-8");
```
使用Charset类进行加码和解码操作:
```java
String str = "Hello World";
// 将字符串转换为字节数组,使用UTF-8编码
byte[] bytes = str.getBytes(Charset.forName("UTF-8"));
// 将字节数组转换为字符串,使用UTF-8编码
String str2 = new String(bytes, Charset.forName("UTF-8"));
```
使用Base64类进行加码和解码操作:
```java
String str = "Hello World";
// 将字符串进行Base64编码
String encodedStr = Base64.getEncoder().encodeToString(str.getBytes());
// 将Base64编码的字符串进行解码
byte[] decodedBytes = Base64.getDecoder().decode(encodedStr);
String decodedStr = new String(decodedBytes);
```
以上是Java中常见的加码和解码操作,具体使用哪种方式取决于具体的需求和使用场景。
阅读全文
相关推荐










