Base64 妙用

 

一、文件转换

 

1、文件转为Base64

    public String encryptToBase64(String filePath) {
        if (filePath == null) {
            return null;
        }
        try {
            byte[] b = Files.readAllBytes(Paths.get(filePath));
            return Base64.getEncoder().encodeToString(b);
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        return null;
    }    

将文件读成二进制码,然后通过Base64.getEncoder().encodeToString()方法将二进制码转换为Base64值。

 

2、Base64转为文件:

    public String decryptByBase64(String base64, String filePath) {
        if (base64 == null && filePath == null) {
            return "生成文件失败,请给出相应的数据。";
        }
        try {
            Files.write(Paths.get(filePath), Base64.getDecoder().decode(base64),StandardOpenOption.CREATE);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "指定路径下生成文件成功!";
    }

 

字符串参数base64指的是文件的Base64值,filePath是指的文件将要保存的位置。
通过Files.write()方法轻松将文件写入指定位置,不再调用FileOutStream方法。

第三个参数StandardOpenOption.CREATE是处理文件的方式,我设置的是不管路径下有或没有,都创建这个文件,有则覆盖。

在StandardOpenOption类中有很多参数可调用,不再累赘。

 

 

 字符串编码加密

UtilsForJdk8


(也可以直接使用 org.springframework.util.Base64Utils ,不用封装)
在Java中,Base64编码和解码是Java平台的一部分,因此不需要额外安装任何库即可使用。
Base64是一种用64个字符表示任意二进制数据的方法,常用于在文本环境中存储二进制数据(如图片、音频、视频等)。

从Java 8开始,java.util.Base64类提供了简单的方法来执行Base64编码和解码。

import org.springframework.util.Base64Utils;

/**
 * @ClassDescription: 直接使用java自带的Base64Utils工具封装的加解密方法
 * @JdkVersion: 1.8
 */
public class Base64Utils {
    /**
     * 加密
     * @param str 需要加密的字符串
     * @return 加密后的字符串
     */
    public static String base64UtilsEncrypt(String str){
        return Base64Utils.encodeToString(str.getBytes());
    }

    /**
     * 解密
     * @param str 需要解密的字符串
     * @return 解密后的字符串
     */
    public static String base64UtilsDecrypt(String str){
        byte[] bytes = Base64Utils.decodeFromString(str);
        return new String(bytes);
    }
}

 

import java.util.Base64;
 
public class Base64Example {
    public static void main(String[] args) {
        String originalString = "Hello, World!";
        
        // 使用Base64编码
        String encodedString = Base64.getEncoder().encodeToString(originalString.getBytes());
        System.out.println("Encoded: " + encodedString);

        String encodedString = "SGVsbG8sIFdvcmxkIQ=="; // "Hello, World!" 的Base64编码    
        // 使用Base64解码
        byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
        String decodedString = new String(decodedBytes);
        System.out.println("Decoded: " + decodedString);
    }
}

 

jdk6

如果你使用的是JDK版本低于8,可以使用Apache Commons Codec库来进行Base64编码和解码。首先需要添加Apache Commons Codec的依赖:

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.15</version> <!-- 请检查最新版本 -->
</dependency>
import org.apache.commons.codec.binary.Base64;
 
public class Base64Example {
    public static void main(String[] args) {
        String originalString = "Hello, World!";
        
        // 使用Apache Commons Codec进行Base64编码
        byte[] encodedBytes = Base64.encodeBase64(originalString.getBytes());
        String encodedString = new String(encodedBytes); // 注意:这里直接转换为字符串可能不是最优雅的方式,因为可能会有不可见字符。通常我们这样使用:
        String encodedStringClean = new String(encodedBytes, StandardCharsets.UTF_8); // 更推荐使用标准字符集转换以避免问题。
        System.out.println("Encoded: " + encodedStringClean);


        String encodedString = "SGVsbG8sIFdvcmxkIQ=="; // "Hello, World!" 的Base64编码字符串。
        byte[] decodedBytes = Base64.decodeBase64(encodedString); // 使用Apache Commons Codec进行Base64解码。
        String decodedString = new String(decodedBytes, StandardCharsets.UTF_8); // 正确的字符集转换。
        System.out.println("Decoded: " + decodedString); // 输出解码后的字符串。
    }
}

 

posted @ 2025-07-14 09:51  吹梦到西州  阅读(53)  评论(0)    收藏  举报