Java Built-In Implementation of MIME Base64

This section provides a tutorial example on how to perform Base64 encoding on binary files with both standard and MIME options using the default Java implementation of the Base64 encoding algorithm.

Java also offers a variation of the Base64 algorithm called MIME (Multipurpose Internet Mail Extensions) Encoder, which wraps the encoded output into 76 characters to meet the MIME specification.

To perform MIME Base64 encoding, you need to call Base64.getMimeEncoder() to create a MIME Base64 encoder.

Here is a sample program that allows you to perform Base64 encoding on any given file with both standard and MIME options:

 * Copyright (c) 2002 All Rights Reserved.
import java.util.Base64;
class Base64MimeEncoder {
  public static void main(String[] args) {
    if (args.length<2) {
       System.out.println("java input_file mime");
    String fileName = args[0];
    String mime = args[1];
    try {
      File file = new File(fileName);
      long length = file.length();
      FileInputStream inputStream = new FileInputStream(file);
      byte[] inputBytes = new byte[(int)length];
      int l =;
      Base64.Encoder encoder = null;
      if (mime.equals("mime")) {
        encoder = Base64.getMimeEncoder();
      } else {
        encoder = Base64.getEncoder();
      byte[] encodedBytes = encoder.encode(inputBytes);
      System.out.println(new String(encodedBytes));
    } catch (Exception e) {

To try the above program, you can download the binary image file from my Website:

herong> curl > icon.png  

Now encode this binary file with both MIME and standard option:

herong> java icon.png mime 

herong> java icon.png standard 

As you can see, the MIME Base64 encoding is identical to the standard Base64 encoding, except that it adds line breaks to keep the output in 76-character line format.

According the Base64 specification, adding line breaks and other whitespaces in the encoded output is allowed.

Table of Contents

 About This Book

 Base64 Encoding

Base64 Encoding and Decoding Tools

 Base64.Guru - Base64 Online Tool

 Windows Command - "certutil -encode/-decode"

 Linux Command - "base64"

 macOS Command - "base64"

 Java Built-In Implementation of Base64

Java Built-In Implementation of MIME Base64

 Python Built-In Implementation of Base64

 Python Built-In Implementation of MIME Base64

 PHP Built-In Implementation of Base64

 PHP Built-In Implementation of MIME Base64

 Perl Built-In Implementation of Base64

 Perl Built-In Implementation of MIME Base64

 Base64URL - URL Safe Base64 Encoding

 Base32 Encoding

 URL Encoding, URI Encoding, or Percent Encoding

 UUEncode Encoding


 Full Version in PDF/EPUB