Java base64 encoding/decoding?

Java base64 encoding/decoding?

In Java, you can encode and decode data in Base64 format using the java.util.Base64 class, which is available in Java 8 and later. Here are examples of how to perform Base64 encoding and decoding:

Base64 Encoding:

To encode data in Base64 format, you can use the java.util.Base64 class's getEncoder() method and call the encodeToString() method to obtain the Base64-encoded string.

import java.util.Base64; public class Base64EncodingExample { public static void main(String[] args) { String originalText = "Hello, Base64 Encoding!"; // Encode the string to Base64 byte[] encodedBytes = Base64.getEncoder().encode(originalText.getBytes()); String encodedString = new String(encodedBytes); System.out.println("Original Text: " + originalText); System.out.println("Encoded Text: " + encodedString); } } 

Base64 Decoding:

To decode data from Base64 format, you can use the java.util.Base64 class's getDecoder() method and call the decode() method to obtain the decoded byte array.

import java.util.Base64; public class Base64DecodingExample { public static void main(String[] args) { String encodedText = "SGVsbG8sIEJhc2U2NCBEZWNvZGluZyE="; // Decode the Base64-encoded string byte[] decodedBytes = Base64.getDecoder().decode(encodedText); String decodedString = new String(decodedBytes); System.out.println("Encoded Text: " + encodedText); System.out.println("Decoded Text: " + decodedString); } } 

In these examples:

  • For encoding, we first convert the original text into bytes, then encode those bytes into a Base64 string.

  • For decoding, we take the Base64-encoded string, decode it into bytes, and then convert the bytes back into a string.

Base64 encoding is commonly used for various purposes, such as encoding binary data as text for transmission over text-based protocols or embedding binary data in JSON or XML payloads.


More Tags

textwrangler oledbdataadapter hash natural-join avconv urlconnection ipc information-visualization line-count file-descriptor

More Java Questions

More Financial Calculators

More Physical chemistry Calculators

More Transportation Calculators

More Tax and Salary Calculators