工作小记

Base64Utils

2020-03-30  本文已影响0人  叫子非鱼啊
base64的相关功能类

关于base64常用的功能也就是一下四个了,最常用还是文件和base64的互转。毕竟很方便,缺点就是要注意文件转base64编码的大小了。毕竟编码后的字符串要比原文件大很多的。具体可以查看Base64编码的原理。
对于String和base64的编码和解码,觉得用到的地方真的不多,达不到加密的效果。用这种实现加解密真的只能说是掩耳盗铃,欺骗自己的眼睛,达不到真的加密效果(如果说我们平常看到的是白话文,那它就是文言文,需要我们稍微的做一些翻译,至于翻译呢,谁都可以把它转换成最开始的白话文)。
但是文件和Base64编码的字符串就很有用了,多个系统之间文件的传输必不可少。

package com.demo;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
 * base64的相关功能类<br>
 *    文件转base64
 * <br>
 *    base64转文件
 * <br>
 *    String 转 Base64
 * <br>
 *    base64转String
 * 
 * @author lxh96
 *
 */
public class Base64Utils {
    public static void main(String[] args) throws Exception {

        //本地文件地址
        String filePath = "C:/Users/lxh96/Pictures/B01.jpg";
        String str = FileToBase64ByLocal(filePath);
        System.out.println(str);
        //在线文件地址
        String string = "https://upload.jianshu.io/users/upload_avatars/20442147/dbfd2e04-5282-4091-b683-b5871f8af36e.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/240/h/240";
        String str1 = FileToBase64ByOnline(string);
        System.out.println(str1);

        // 字符串转换成base64
        String string2 = "hello world!!!---- 你好!!";
        String str2 = strConvertBase64(string2);
        System.out.println(str2);

        // base64转换成String
        System.out.println(Base64ConvertStr(str2));

        // base64转成文件
//      System.out.println("生成文件"+Base64Utils.decoderBase64File(str, "C:/Users/lxh96/Pictures/test.png"));

    }

    /**
     * 本地文件转换成base64字符串
     * 
     * @param filePath
     * @return String
     */
    public static String FileToBase64ByLocal(String filePath) {// 将文件文件转化为字节数组字符串,并对其进行Base64编码处理

        InputStream in = null;
        byte[] data = null;

        // 读取文件字节数组
        try {
            in = new FileInputStream(filePath);

            data = new byte[in.available()];
            in.read(data);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(in == null) {
                try {
                    in.close();
                } catch (IOException e) {
                    System.out.println("流关闭异常"+e);
                }
            }
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();

        return encoder.encode(data);// 返回Base64编码过的字节数组字符串
    }

    /**
     * 在线文件转换成base64字符串
     * 
     * @param fileURL
     * @return String
     */
    public static String FileToBase64ByOnline(String fileURL) {
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        InputStream is = null ;
        try {
            // 创建URL
            URL url = new URL(fileURL);
            byte[] by = new byte[1024];
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            is = conn.getInputStream();
            // 将内容读取内存中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 关闭流
            try {
                is.close();
            } catch (IOException e) {
                System.out.println("流关闭异常"+e);
            }
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data.toByteArray());
    }

    /**
     * 将base64字符解码保存文件
     * 
     * @param base64Code 解码
     * @param targetPath 要存的地址
     * @return String 路径
     */

    public static String decoderBase64File(String base64Code, String targetPath) {
        File file = new File(targetPath);
        FileOutputStream out = null;
        try {
            if (file.exists()) {
                System.out.println(targetPath + " 文件已经存在,不能转换为文件");
                return null;
            } else {
                boolean createNewFile = file.createNewFile();
                if (createNewFile) {
                    System.out.println("文件创建成功!");
                } else {
                    System.out.println("文件创建遇到问题。");
                }
            }
            byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
            out = new FileOutputStream(targetPath);
            out.write(buffer);
            System.out.println("文件保存成功!");
        } catch (Exception e) {
            System.out.println("文件base64编码转换失败!" + e);
            targetPath = "";
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        return targetPath;
    }

    /**
     * 将字符串转换成Base64编码
     * 
     * @param tagertStr 要转换的字符串
     * @return String base64编码后的字符串
     */
    public static String strConvertBase64(String tagertStr) {
        byte[] value;
        try {
            value = tagertStr.getBytes("UTF-8");
            BASE64Encoder encoder = new BASE64Encoder();
            return new String(encoder.encode(value));
        } catch (Exception e) {
            System.out.println("字符串base64编码转换失败!" + e);
        }
        return null;
    }

    /**
     * base64解码转String UTF-8
     * @param base64Str
     * @return String
     */
    public static String Base64ConvertStr(String base64Str) {
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bytes = decoder.decodeBuffer(base64Str);
            return new String(bytes, "UTF-8");
        } catch (Exception e) {
            System.out.println("base64转String失败!" + e);
        }
        return null;
    }
}

代码参考网络,对里边的一些方法进行了稍微的修改。将关闭流放在了finally中,因为关闭前如果报错,直接走进catch中,会导致流不能正常关闭。

至于输入输出流不关闭的影响,会在之后的文章中介绍(请给我一些测试的时间)。

本想文章中放一些美食的图片,想想还是算了吧,怕你们文章没看完出去点外卖了。

上一篇下一篇

猜你喜欢

热点阅读