Java.Java8.What class was introduced in Java 8 for encoding/decoding data?

🧩 In Java 8, the class introduced for encoding and decoding data, especially in Base64, is:


java.util.Base64

This class provides built-in support for Base64 encoding and decoding — no more need for third-party libraries or Apache Commons!


🔹 Why It Was Added

Before Java 8, developers had to use:

  • sun.misc.BASE64Encoder (non-standard)
  • Apache Commons Codec
  • Bouncy Castle

Java 8 finally introduced a standardized, simple, and secure solution in the JDK.


✅ How to Use Base64

🔹 1. Basic Base64 Encoding/Decoding

import java.util.Base64;

public class Base64Example {
    public static void main(String[] args) {
        String text = "Hello, Stanley!";
        
        // Encode
        String encoded = Base64.getEncoder().encodeToString(text.getBytes());
        System.out.println("Encoded: " + encoded);
        
        // Decode
        byte[] decodedBytes = Base64.getDecoder().decode(encoded);
        String decoded = new String(decodedBytes);
        System.out.println("Decoded: " + decoded);
    }
}

🔹 Output:

Encoded: SGVsbG8sIFN0YW5sZXkh
Decoded: Hello, Stanley!

🔧 Types of Base64 Encoders in Java 8

MethodDescription
Base64.getEncoder()Standard Base64
Base64.getUrlEncoder()URL and filename-safe Base64 (no +, /)
Base64.getMimeEncoder()MIME Base64 with line breaks every 76 characters
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.