在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!
這些是常用的編碼和解碼方法的示例。根據具體的需求和使用場景,可以選擇適合的編碼和解碼方法。