Beispiel für Codierung und Decodierung in Java

Until Java 8, there was no standard way to Base64 encode a String in Java or decode a base64 encoded String. Java Programmers either use Apache Commons library and it's Base64 class to encode or decode binary data into base 64 encoding or rely on internal Sun classes e.g. sun.misc.BASE64Encoder and sun.misc.BASE64Decoder(), which were not officially part of JDK and can be removed without notification. Java 8 solves this problem by providing standard support for base64 encoding and decoding by providing a java.util.Base64 class. This class contains methods like getEncoder() and getDecoder() to provide Base64 encoder and decoder to carry out base 64 encoding of String or binary data. In this article, I'll show you some example of how to base64 encode String in Java 8.

Java 8 provides three types of base64 encoding and corresponding built-in encoder and decoder, as shown below.

Basic Base64 Encoder In this type of encoder, only characters A-Z a-z0-9+/ are used for base64 encoding. The encoder does not add any line feed in the output, and the decoder rejects any character other than A-Za-z0-9+/. That's why you see a big line of alphanumeric characters. This is the one you will use most likely and we'll see examples of this Base64 encoder in this tutorial.

You can use the static getEncoder() and getDecoder() method of Base64 class to obtain the basic base64 encoder and decoder and use their encode() and decode() for base64 encoding and decoding.

URL Base64 Encoder This is similar to basic type but instead of "", underscore ("") is used i.e. only characters A-Za-z0-9+ are supported. The key point about this encoder is that output is also URL and filename safe because there is no "" character which acts as the path separator in many operating systems e.g. Windows.

You can use the getUrlEncoder() and getUrlDecoder() method to get the encoder and decoder who can perform this type of base64 encoding.

MIME Base64 Encoder This is the third type of base64 encoding supported by Java 8. In this case, the output is mapped to MIME-friendly format. The output is represented in lines of no more than 76 characters each and uses a carriage return '\r' followed by a linefeed '\n' as the line separator. No line separator is present to the end of the encoded output.

You can use the static method getMimeEncoder() and getMimeDecoder() to get the MIME type base64 encoder and decoder with specified line length and line separators.

Base64 Encoding Example in Java 8 Now, let's an example of how to encode String into base64 encoding in Java 8. Here is our sample Java program which demonstrates base64 encoding and decoding in basic, URL and MIME types.

For those who are not very familiar with base64 encoding in general, here is good slide to recap the fundamentals:

Java program for base64 encoding and decoding String import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.Base64.Decoder; import java.util.Base64.Encoder;

/*

*/ public class PascalTriangleInJava {

public static void main(String[] args) {

    // Encoding String using basic base64 encoder
    Encoder theEncoder = Base64.getEncoder();
    String original = "Minecraft";
    byte[] theArray = original.getBytes(StandardCharsets.UTF_8);
    String base64encodedString = theEncoder.encodeToString(theArray);
    System.out.println("Original String: " + original);
    System.out.println("Base64 Encoded String :" + base64encodedString);

    // Decoding a base64 encoded String in Java 8
    Decoder theDecoder = Base64.getDecoder();
    byte[] byteArray = theDecoder.decode(base64encodedString);
    String decoded = new String(byteArray, StandardCharsets.UTF_8);
    System.out.println("decoded String: " + decoded);

}

}

Output Original String: Minecraft Base64 Encoded String :TWluZWNyYWZ0 decoded String: Minecraft

That's all about how to encode String in base64 in Java 8. Now, there is no need to use the Apache commons Code library (an additional dependency on the third-party library) or non-standard sun.misc.BASE64Encoder class for base64 encoding. You should only use the new java.util.Base64 class for encoding and decoding String or byte array into Base64. In the next part of this article, I'll teach you how to decode a Base64 encoded String in Java 8.

Related blog:

Spring rest interview questions

Spring boot interview questions

Recommended Posts

Beispiel für Codierung und Decodierung in Java
Ändern Sie die Java-Codierung in Windows
StringBuffer- und StringBuilder-Klasse in Java
Verstehe gleich und hashCode in Java
Hallo Welt in Java und Gradle
Unterschied zwischen final und Immutable in Java
Parallelitätsmethode in Java mit grundlegendem Beispiel
Unterschied zwischen Arrylist und verknüpfter Liste in Java
Programmieren Sie PDF-Kopf- und Fußzeilen in Java
Lernen Sie Flyweight-Muster und ConcurrentHashMap in Java
Die Richtung von Java in "C ++ Design and Evolution"
Von Java nach C und von C nach Java in Android Studio
Lesen und Schreiben von GZIP-Dateien in Java
Unterschied zwischen int und Integer in Java
Diskriminierung von Enum in Java 7 und höher
Partisierung in Java
Änderungen in Java 11
Janken in Java
Java und JavaScript
XXE und Java
Umfangsrate in Java
FizzBuzz in Java
In Bezug auf transiente Modifikatoren und Serialisierung in Java
Erkennen Sie ähnliche Videos in Java und OpenCV Version 2
Parallele und parallele Verarbeitung in verschiedenen Sprachen (Java Edition)
Unterschied zwischen next () und nextLine () in Java Scanner
Unterschiede beim Schreiben von Java-, C # - und Javascript-Klassen
Erfassen und speichern Sie die Selen-Installation in Java
Erkennen Sie ähnliche Videos in Java und OpenCV Version 3
Hinzufügen, Lesen und Löschen von Excel-Kommentaren mit Java
Überprüfen Sie das statische und öffentliche Verhalten in Java-Methoden
[Java] Verstehe in 10 Minuten! Assoziatives Array und HashMap
Unterscheiden Sie in Java zwischen positiven und negativen Zahlen
Java fügt Wasserzeichen in Word-Dokumenten hinzu und entfernt sie
Erkennen Sie ähnliche Videos in Java und OpenCV Version 1
Repräsentiert "nächster Tag" und "vorheriger Tag" in Java / Android
Fragen in Java-Ausnahmebehandlung werfen und versuchen-fangen
Laden Sie Notizen in Java auf S3 hoch und laden Sie sie herunter
Verschlüsseln / Entschlüsseln mit AES256 in PHP und Java
Generieren Sie OffsetDateTime aus Clock und LocalDateTime in Java
Lesen Sie JSON in Java
Interpreter-Implementierung durch Java
Machen Sie einen Blackjack mit Java
[Android / Java] Bildschirmübergang und Rückgabeverarbeitung in Fragmenten
Versuchte Mastodons Toot- und Streaming-API in Java
Janken App in Java
Anwendungsbeispiel für Java Enum
Schreiben Sie ABNF in Java und geben Sie die E-Mail-Adresse weiter
NVL-artiger Typ in Java
Verbinden Sie Arrays in Java
Getter und Setter (Java)
"Hallo Welt" in Java
Aufrufbare Schnittstelle in Java
[Java] Thread und ausführbar
Java wahr und falsch
Kommentare in der Java-Quelle
Organisieren Sie Builds in C ++ / Java- und Win / Linux-Kombinationen