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

Java中常用的字符编码转换函数

发布时间:2023-07-06 09:57:27

Java中常用的字符编码转换函数有很多,下面列举了一些常用的编码转换函数:

1. String.getBytes(String charsetName):将字符串按指定的字符集编码转换成字节数组。

   例如:String str = "Hello World";

         byte[] bytes = str.getBytes("UTF-8");

2. new String(byte[] bytes, String charsetName):将字节数组按指定的字符集解码为字符串。

   例如:byte[] bytes = {72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100};

         String str = new String(bytes, "UTF-8");

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

   例如:String url = "https://www.example.com?param=" + URLEncoder.encode("编码测试", "UTF-8");

4. URLDecoder.decode(String s, String enc):将URL编码字符串进行解码。

   例如:String url = "https%3A%2F%2Fwww.example.com%3Fparam%3D%E7%BC%96%E7%A0%81%E6%B5%8B%E8%AF%95";

         String decodedUrl = URLDecoder.decode(url, "UTF-8");

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

   例如:String str = "Hello World";

         byte[] bytes = str.getBytes("UTF-8");

         String base64Str = Base64.getEncoder().encodeToString(bytes);

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

   例如:String base64Str = "SGVsbG8gV29ybGQ=";

         byte[] bytes = Base64.getDecoder().decode(base64Str);

         String str = new String(bytes, "UTF-8");

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

   例如:byte[] bytes = {72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100};

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

上述函数中常用的字符集包括UTF-8、GBK、ISO-8859-1等。

这些字符编码转换函数在Java开发中非常常用,能够用于处理文件编码、URL编码、Base64编码等业务需求。通过合理使用这些函数,能够有效地处理字符编码转换的问题。