Java中提供了Base64编码和解码的工具类java.util.Base64,使用该类可以方便地进行Base64编码和解码操作。

以下是使用java.util.Base64进行Base64编码的示例代码:

import java.util.Base64;

public class Base64Example {
    public static void main(String[] args) {
        String text = "Hello, world!";
        byte[] textBytes = text.getBytes();

        byte[] encodedBytes = Base64.getEncoder().encode(textBytes);
        String encodedText = new String(encodedBytes);
        System.out.println("Base64 encoded text: " + encodedText);
    }
}

输出结果为:

Base64 encoded text: SGVsbG8sIHdvcmxkIQ==

以上代码中,首先将待编码的字符串转换为字节数组,然后使用Base64.getEncoder().encode()方法对字节数组进行Base64编码,得到编码后的字节数组,最后将字节数组转换为字符串输出。

使用java.util.Base64进行Base64解码的示例代码如下:

import java.util.Base64;

public class Base64Example {
    public static void main(String[] args) {
        String encodedText = "SGVsbG8sIHdvcmxkIQ==";
        byte[] encodedBytes = encodedText.getBytes();

        byte[] decodedBytes = Base64.getDecoder().decode(encodedBytes);
        String decodedText = new String(decodedBytes);
        System.out.println("Base64 decoded text: " + decodedText);
    }
}

输出结果为:

Base64 decoded text: Hello, world!

以上代码中,首先将待解码的字符串转换为字节数组,然后使用Base64.getDecoder().decode()方法对字节数组进行Base64解码,得到解码后的字节数组,最后将字节数组转换为字符串输出。

java base64编码

原文地址: https://www.cveoy.top/t/topic/FoL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录