欢迎访问宙启技术站
智能推送

Java中编码和解码字符串的函数

发布时间:2023-07-04 06:47:05

在Java中,编码和解码字符串的函数主要涉及到对字符集的转换和处理。下面是一些常见的编码和解码字符串的函数及其用法。

1. 编码字符串为字节序列函数:

- getBytes():将字符串编码为字节数组。默认使用平台的默认字符集,也可以指定字符集作为参数。

示例:

     String str = "Hello World";
     byte[] bytes = str.getBytes(); // 默认编码方式
     byte[] utf8Bytes = str.getBytes("UTF-8"); // 指定UTF-8编码
     

2. 解码字节序列为字符串函数:

- String(byte[] bytes):使用默认字符集将字节数组解码为字符串。

- new String(byte[] bytes, Charset charset):使用指定的字符集将字节数组解码为字符串。

示例:

     byte[] bytes = {72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100};
     String str1 = new String(bytes); // 默认解码方式
     String str2 = new String(bytes, "UTF-8"); // 指定UTF-8解码
     

3. URL编码和解码:

- URLEncoder.encode(String s, String enc):将字符串进行URL编码。

- URLDecoder.decode(String s, String enc):将经过URL编码的字符串进行解码。需要注意,解码时需要传入和编码时相同的字符集参数。

示例:

     String url = "https://www.example.com/搜索?q=Java编码";
     String encodedUrl = URLEncoder.encode(url, "UTF-8");
     String decodedUrl = URLDecoder.decode(encodedUrl, "UTF-8");
     

4. Base64编码和解码:

- Base64.getEncoder().encodeToString(byte[] src):将字节数组进行Base64编码。

- Base64.getDecoder().decode(String src):将经过Base64编码的字符串进行解码。

示例:

     byte[] data = "Hello World".getBytes();
     String encodedData = Base64.getEncoder().encodeToString(data);
     byte[] decodedData = Base64.getDecoder().decode(encodedData);
     String str = new String(decodedData);
     

5. HTML编码和解码:

- StringEscapeUtils.escapeHtml4(String input):将字符串中的HTML特殊字符进行编码。

- StringEscapeUtils.unescapeHtml4(String input):将经过HTML编码的字符串进行解码。

示例:

     String html = "<p>Hello World</p>";
     String escapedHtml = StringEscapeUtils.escapeHtml4(html);
     String unescapedHtml = StringEscapeUtils.unescapeHtml4(escapedHtml);
     

这些是Java中经常用到的一些编码和解码字符串的函数,使用这些函数可以方便地进行字符串的编码和解码操作。需要注意的是,在使用不同的编码方式时,要确保编码和解码的字符集一致,以免导致乱码或解码失败的问题。