java encode和decode怎么使用

avatar
作者
猴君
阅读量:0

在Java中,编码和解码通常用于将数据从一种格式转换为另一种格式。以下是一些常用的编码和解码方法的示例:

  1. 使用Base64编码和解码字符串:
import java.util.Base64; String originalString = "Hello, World!"; String encodedString = Base64.getEncoder().encodeToString(originalString.getBytes()); String decodedString = new String(Base64.getDecoder().decode(encodedString)); System.out.println("Encoded string: " + encodedString); System.out.println("Decoded string: " + decodedString); 

输出结果:

Encoded string: SGVsbG8sIFdvcmxkIQ== Decoded string: Hello, World! 
  1. 使用URL编码和解码字符串:
import java.net.URLEncoder; import java.net.URLDecoder; String originalString = "Hello, World!"; String encodedString = URLEncoder.encode(originalString, "UTF-8"); String decodedString = URLDecoder.decode(encodedString, "UTF-8"); System.out.println("Encoded string: " + encodedString); System.out.println("Decoded string: " + decodedString); 

输出结果:

Encoded string: Hello%2C+World%21 Decoded string: Hello, World! 
  1. 使用UTF-8编码和解码字符串:
import java.nio.charset.StandardCharsets; String originalString = "Hello, World!"; byte[] encodedBytes = originalString.getBytes(StandardCharsets.UTF_8); String encodedString = new String(encodedBytes, StandardCharsets.UTF_8); String decodedString = new String(encodedBytes, StandardCharsets.UTF_8); System.out.println("Encoded string: " + encodedString); System.out.println("Decoded string: " + decodedString); 

输出结果:

Encoded string: Hello, World! Decoded string: Hello, World! 

这些是常用的编码和解码方法的示例。根据具体的需求和使用场景,可以选择适合的编码和解码方法。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!