Java 8 Encode/Decode base64 Example

Java 8 Encode/Decode base64 Example explains about encoding and decoding of a Base64 string using java 8

I have already wrote an article Encode And Decode In Base64 Using Java before 3 years, about encoding/decoding base64 formatted string using different java third party api's. This is because in that days, there is no decent api is available for encode/decode a string into base64

Finally Java 8 included new feature to encode/decode base64 string without the help of any third party libraries

Java 8 Base64 class consists exclusively of static methods for obtaining encoders and decoders for the Base64 encoding scheme. The implementation of this class supports the following types of Base64 as specified in RFC 4648 and RFC 2045.

  • Basic

    Uses "The Base64 Alphabet" as specified in Table 1 of RFC 4648 and RFC 2045 for encoding and decoding operation. The encoder does not add any line feed (line separator) character. The decoder rejects data that contains characters outside the base64 alphabet.

  • URL and Filename safe

    Uses the "URL and Filename safe Base64 Alphabet" as specified in Table 2 of RFC 4648 for encoding and decoding. The encoder does not add any line feed (line separator) character. The decoder rejects data that contains characters outside the base64 alphabet.

  • MIME

    Uses the "The Base64 Alphabet" as specified in Table 1 of RFC 2045 for encoding and decoding operation. The encoded output must be represented in lines of no more than 76 characters each and uses a carriage return '\r' followed immediately by a linefeed '\n' as the line separator. No line separator is added to the end of the encoded output. All line separators or other characters not found in the base64 alphabet table are ignored in decoding operation.

Reference -> http://docs.oracle.com/javase/8/docs/api/java/util/Base64.html

Java 8 new api is available in java.util.Base64, you need to import the package (Please see below example)

Java 8 Encode/Decode base64 Example

import java.util.Base64;

public class Base64Test {

 
public static void main(String[] args) {
   
//Encode base 64
     
String encodedBytes = Base64.getEncoder().encodeToString("JavaTips.net".getBytes("utf-8"));
      System.out.println
("encodedBytes " + encodedBytes);
     
//Decode base 64
     
byte[] decodedBytes = Base64.getDecoder().decode(encodedBytes);
      System.out.println
("decodedBytes " + new String(decodedBytes));
 
}
}
Output
encodedBytes SmF2YVRpcHMubmV0

decodedBytes JavaTips.net










1 Responses to "Java 8 Encode/Decode base64 Example"
  1. code beautify 2019-10-19 00:59:21.0

Your email address will not be published. Required fields are marked *