在Java中,编码和解码通常用于将数据从一种格式转换为另一种格式。以下是一些常用的编码和解码方法的示例:
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!
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!
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!
这些是常用的编码和解码方法的示例。根据具体的需求和使用场景,可以选择适合的编码和解码方法。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: java如何下载文件到本地