Java 简明教程

Java - Base64 Encoding and Decoding

Java 8 中引入了 Base64 实用程序类,它具有针对 Base64 encoding and decoding 的内置编码器和解码器。我们提供了三种类型的 Base64 编码和解码操作。以下是添加这些类型的摘要:

The Base64 utility class was introduced in Java 8 that has inbuilt encoder and decoder for Base64 encoding and decoding. We’ve three types of Base64 encoding and decoding available. Following is a brief of these types added:

  1. Basic − Output is mapped to a set of characters lying in A-Za-z0-9+/. The encoder does not add any line feed in output, and the decoder rejects any character other than A-Za-z0-9+/.

  2. URL − Output is mapped to set of characters lying in A-Za-z0-9+_. Output is URL and filename safe.

  3. MIME − Output is mapped to MIME friendly format. 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.

Basic Base64 Encoding and Decoding

Basic Base64 编码器对提供的字符串进行编码,而不添加任何换行符。此编码器使用位于 A-Za-z0-9+/ 字符集中的字符。以下是说明使用 Base64 编码器的代码片段。

Basic Base64 encoder encodes the provided string without adding any line feed. This encoder uses characters lying in A-Za-z0-9+/ character set. Following is the snippet explaining the use of Base64 encoder.

String stringToEncode = "TutorialsPoint?java8";
// Encode using basic encoder
String base64encodedString = Base64.getEncoder().encodeToString(stringToEncode.getBytes("utf-8"));

Simple Base64 解码器通过拒绝所有除 A-Za-z0-9+/ 之外的字符来解码 Base64 编码的字符串。以下是说明使用 Base64 解码器的代码片段。

Simple Base64 decoder decodes the Base64 encoded string by rejecting any character other than A-Za-z0-9+/. Following is the snippet explaining the use of Base64 decoder.

// Decode the base64 encoded string using basic decoder
byte[] base64decodedBytes = Base64.getDecoder().decode(base64encodedString);
// print the decoded string
System.out.println("Original String: " + new String(base64decodedBytes, "utf-8"));

Example: Basic Base64 Encoding and Decoding in Java

以下示例展示了 Basic Base64 编码器和解码器的用法。我们首先使用通过 Base64.getEncoder() 获取的编码器对一个简单字符串进行编码,然后使用通过 Base64.getDecoder() 方法获取的解码器对返回的编码字符串进行解码。

Following example showcases the use of Base64 basic encoder and decoder. We’ve first encoded a simple string using a encoder retrieved using Base64.getEncoder() and then returned encoded string is decoded using decoder retrieved using Base64.getDecoder() method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

public class Base64Tester {
   public static void main(String[] args) throws UnsupportedEncodingException {
      String stringToEncode = "TutorialsPoint?java";
      // Encode using basic encoder
      String base64encodedString = Base64.getEncoder().encodeToString(stringToEncode.getBytes("utf-8"));
      System.out.println("Encoded String: " + base64encodedString);

      // Decode the base64 encoded string using basic decoder
      byte[] base64decodedBytes = Base64.getDecoder().decode(base64encodedString);
      // print the decoded string
      System.out.println("Decoded String: " + new String(base64decodedBytes, "utf-8"));
   }
}

让我们编译并运行上述程序,这将生成以下结果 −

Let us compile and run the above program, this will produce the following result −

Encoded String: VHV0b3JpYWxzUG9pbnQ/amF2YQ==
Decoded String: TutorialsPoint?java

Base64 Encoding and Decoding for URL

URL Base64 编码器对提供的 URL 进行编码,并使其成为 URL 和文件名安全的。此编码器使用位于 A-Za-z0-9+/ 字符集中的字符。它使用 URL 和文件名安全类型 base64 编码方案进行编码。以下是说明使用 URL Base64 编码器的代码片段。

URL Base64 encoder encodes the provided URL and makes it URL and filename safe. This encoder uses characters lying in A-Za-z0-9+/ character set. It encodes using the URL and Filename safe type base64 encoding scheme. Following is the snippet explaining the use of URL Base64 encoder.

String stringToEncode = "TutorialsPoint?java8";
// Encode using url encoder
String base64encodedString = Base64.getUrlEncoder().encodeToString(stringToEncode.getBytes("utf-8"));

URL Base64 解码器通过拒绝所有除 A-Za-z0-9+/ 之外的字符来解码 Base64 编码的字符串。它使用 URL 和文件名安全类型 base64 编码方案进行解码。以下是说明 Base64 解码器用法的代码片段。

URL Base64 decoder decodes the Base64 encoded string by rejecting any character other than A-Za-z0-9+/. It decodes using the URL and Filename safe type base64 encoding scheme. Following is the snippet explaining the use of Base64 decoder.

// Decode the base64 encoded string using basic decoder
byte[] base64decodedBytes = Base64.getUrlDecoder().decode(base64encodedString);
// print the decoded string
System.out.println("Original String: " + new String(base64decodedBytes, "utf-8"));

Example: Base64 Encoding and Decoding for URL in Java

以下示例展示了 Base64 URL 编码器和解码器的用法。我们首先使用通过 Base64.getUrlEncoder() 获取的编码器对一个简单字符串进行编码,然后使用通过 Base64.getUrlDecoder() 方法获取的解码器对返回的编码字符串进行解码。

Following example showcases the use of Base64 URL encoder and decoder. We’ve first encoded a simple string using a encoder retrieved using Base64.getUrlEncoder() and then returned encoded string is decoded using decoder retrieved using Base64.getUrlDecoder() method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

public class Base64Tester {
   public static void main(String[] args) throws UnsupportedEncodingException {
      String stringToEncode = "TutorialsPoint?java";
      // Encode using url encoder
      String base64encodedString = Base64.getUrlEncoder().encodeToString(stringToEncode.getBytes("utf-8"));
      System.out.println("Encoded String: " + base64encodedString);

      // Decode the base64 encoded string using url decoder
      byte[] base64decodedBytes = Base64.getUrlDecoder().decode(base64encodedString);
      // print the decoded string
      System.out.println("Decoded String: " + new String(base64decodedBytes, "utf-8"));
   }
}

让我们编译并运行上述程序,这将生成以下结果 −

Let us compile and run the above program, this will produce the following result −

Encoded String: VHV0b3JpYWxzUG9pbnQ_amF2YQ==
Decoded String: TutorialsPoint?java

Base64 Encoding and Decoding for MIME Type Content

MIME Base64 编码器将提供的字符串内容编码为 MIME 友好格式。输出以每行不超过 76 个字符的格式表示,并使用回车符 '\r' 后跟换行符 '\n' 作为行分隔符。对编码输出的末尾没有行分隔符。以下是说明 MIME Base64 编码器使用方式的代码片段。

MIME Base64 encoder encodes the provided string content to MIME friendly format. 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. Following is the snippet explaining the use of MIME Base64 encoder.

String stringToEncode = "TutorialsPoint?java8";
// Encode using mime encoder
String base64encodedString = Base64.getMimeEncoder().encodeToString(stringToEncode.getBytes("utf-8"));

MIME Base64 解码器通过拒绝除 A-Za-z0-9+/ 之外的任何字符来解码 Base64 编码字符串。它使用 MIME 类型 base64 解码方案进行解码。以下是说明 Base64 解码器使用方式的代码片段。

MIME Base64 decoder decodes the Base64 encoded string by rejecting any character other than A-Za-z0-9+/. It decodes using the MIME type base64 decoding scheme. Following is the snippet explaining the use of Base64 decoder.

// Decode the base64 encoded string using basic decoder
byte[] base64decodedBytes = Base64.getMIMEDecoder().decode(base64encodedString);
// print the decoded string
System.out.println("Original String: " + new String(base64decodedBytes, "utf-8"));

Example: MIME Base64 Encoding and Decoding in Java

下面的示例展示了 Base64 MIME 编码器和解码器的使用方式。我们首先使用通过 Base64.getMIMEEncoder() 检索的编码器对一个简单的字符串进行了编码,然后使用通过 Base64.getMIMEDecoder() 方法检索的解码器对返回的编码字符串进行了解码。

Following example showcases the use of Base64 MIME encoder and decoder. We’ve first encoded a simple string using a encoder retrieved using Base64.getMIMEEncoder() and then returned encoded string is decoded using decoder retrieved using Base64.getMIMEDecoder() method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.UUID;

public class Base64Tester {
   public static void main(String[] args) throws UnsupportedEncodingException {
      StringBuilder stringBuilder = new StringBuilder();

      for (int i = 0; i < 10; ++i) {
         stringBuilder.append(UUID.randomUUID().toString());
         stringBuilder.append(",");
      }

      byte[] mimeBytes = stringBuilder.toString().getBytes("utf-8");
      String mimeEncodedString = Base64.getMimeEncoder().encodeToString(mimeBytes);
      System.out.println("Base64 Encoded String (MIME) : " + mimeEncodedString);

      // Decode the base64 encoded string using url decoder
      byte[] base64decodedBytes = Base64.getMimeDecoder().decode(mimeEncodedString);
      // print the decoded string
      System.out.println("Decoded String: " + new String(base64decodedBytes, "utf-8"));
   }
}

让我们编译并运行上述程序,这将生成以下结果 −

Let us compile and run the above program, this will produce the following result −

Base64 Encoded String (MIME) : NzRmNjkyODktYzJjZS00ZmU2LWEzYTUtMmFlMWRlMDQ1ZjU4LGQyNGQzMTU5LTVmOGUtNDZhMS04
NGRkLTBiMzNlNzc4ZjNiOCw2MmM1OTEzOS1kNmQwLTQ5MmQtYmUyMi01NmEzMTk5NmRkMTAsZDZh
NjBlNzctZjRjZi00Y2Q4LTk5MWEtYTY2ZDEzMzU4YjFjLGFlNDhkZmZjLTEwZjctNDk5OS05NTFj
LTU5ZGY1MjcyYjczNywxY2JiZjU0Ni0zNjc1LTQ4NzAtYTYxNC01MzkyODFkNjRjYmMsMTlhNTNi
ODEtODQ0OS00M2MyLTg4NmMtNDhmZThmZDZmN2E1LDQyNmRhZDE0LTEyNjItNGJhZC1hMWJlLTNm
ODc4MWE1YzhiMiw2NjEwMTgzZS03MGNkLTQzZTctOTRkNC0wZDgzZmY1MzhkNWYsOWMxNmMwM2Ut
ZWZmZS00Zjg2LWFkYzgtNjc3MThjYTVlYjI2LA==
Decoded String: 74f69289-c2ce-4fe6-a3a5-2ae1de045f58,d24d3159-5f8e-46a1-84dd-0b33e778f3b8,62c59139-d6d0-492d-be22-56a31996dd10,d6a60e77-f4cf-4cd8-991a-a66d13358b1c,ae48dffc-10f7-4999-951c-59df5272b737,1cbbf546-3675-4870-a614-539281d64cbc,19a53b81-8449-43c2-886c-48fe8fd6f7a5,426dad14-1262-4bad-a1be-3f8781a5c8b2,6610183e-70cd-43e7-94d4-0d83ff538d5f,9c16c03e-effe-4f86-adc8-67718ca5eb26,

Nested Classes of Base64 Class

Base64 类提供了以下类。

Following classes are provided by Base64 class.

Sr.No.

Nested class & Description

1

static class Base64.Decoder This class implements a decoder for decoding byte data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045.

2

static class Base64.Encoder This class implements an encoder for encoding byte data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045.

Base64 Class Methods

Base64 类提供了以下方法来帮助进行 Base64 编码/解码。

Following are the methods which provided by Base64 class to assist Base64 encoding/decoding.

Sr.No.

Method Name & Description

1

static Base64.Decoder getDecoder() Returns a Base64.Decoder that decodes using the Basic type base64 encoding scheme.

2

static Base64.Encoder getEncoder() Returns a Base64.Encoder that encodes using the Basic type base64 encoding scheme.

3

static Base64.Decoder getMimeDecoder() Returns a Base64.Decoder that decodes using the MIME type base64 decoding scheme.

4

static Base64.Encoder getMimeEncoder() Returns a Base64.Encoder that encodes using the MIME type base64 encoding scheme.

5

static Base64.Encoder getMimeEncoder(int lineLength, byte[] lineSeparator) Returns a Base64.Encoder that encodes using the MIME type base64 encoding scheme with specified line length and line separators.

6

static Base64.Decoder getUrlDecoder() Returns a Base64.Decoder that decodes using the URL and Filename safe type base64 encoding scheme.

7

static Base64.Encoder getUrlEncoder() Returns a Base64.Encoder that encodes using the URL and Filename safe type base64 encoding scheme.

Methods Inherited

此类从以下类继承方法 −

This class inherits methods from the following class −

  1. java.lang.Object