Encoding and Decoding Strings in Base64 Using Java
Encoding and decoding strings using Base64 is a common task in many programming scenarios. However, specific implementation details can sometimes lead to issues.
The Problem
The provided code snippet appears to encounter problems with encoding and decoding a string in Base64. The specific issue is not explicitly mentioned.
The Solution
To successfully encode and decode strings using Base64 in Java, the following steps must be carefully followed:
Encoding:
Decoding:
Code Example:
A more complete and improved code example that follows the above steps:
import java.nio.charset.StandardCharsets; import java.util.Base64; public class Base64Example { public static void main(String[] args) { String source = "password"; byte[] byteArray = source.getBytes(StandardCharsets.UTF_8); String encodedString = Base64.getEncoder().encodeToString(byteArray); System.out.println("Encoded string: " + encodedString); byte[] decodedByteArray = Base64.getDecoder().decode(encodedString); String decodedString = new String(decodedByteArray, StandardCharsets.UTF_8); System.out.println("Decoded string: " + decodedString); } }
The above is the detailed content of How to Properly Encode and Decode Strings Using Base64 in Java?. For more information, please follow other related articles on the PHP Chinese website!