文件转 Base64 字符串

Java常用方法   2025-04-17 16:21   199   0  
package com;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Main {

    public static void main(String[] args) {

        long start = System.currentTimeMillis();
        File file = new File("D:\\Downloads\\好好國際物流股份有限公司-台湾.pdf");
        String fileName = file.getName();
        String name = fileName.substring(0, fileName.lastIndexOf("."));
        String path = file.getAbsolutePath();
        path = path.substring(0, path.lastIndexOf("\\") + 1);


        //将文件转换为base64字符串
        String contentString = convertFileToBase64(file.getAbsolutePath());

        //将base64字符串内容写入txt文件
        writeToFile(path + name + ".txt", contentString);

        //读取文件里的base64字符串内存
        contentString = readFile(path +name +".txt");

        //将base64字符串转换为正常文件
        generateBase64StringToFile(contentString, path + "new\\" + fileName);

        long end = System.currentTimeMillis();

        System.out.println("转换过程耗时:" + (end - start) + " ms");
    }

    /**
     * 读取文件数据
     * @param strFile
     */
    public static String readFile(String strFile){
        String contentString = "";
        InputStream is = null;
        try{
            is = new FileInputStream(strFile);
            int iAvail = is.available();
            byte[] bytes = new byte[iAvail];
            is.read(bytes);
            is.close();
            contentString = new String(bytes, StandardCharsets.UTF_8);
        }catch(Exception e){
            e.printStackTrace();
        }
        finally {
            try {
                if (null != is) {
                    is.close();
                }
            } catch (Exception e2) {
                // TODO: handle exception
            }
        }
        return contentString;
    }


    /**
     * 写入文件
     * 
     * @param fileName
     * @param content
     * @throws IOException
     */
    public static void writeToFile(String fileName, String content){
        File f1 = new File(fileName);
        OutputStream out = null;
        BufferedWriter bw = null;
        try {
            if (!f1.exists()) {
                mkdirParents(f1);
                if (!f1.createNewFile()) {
                    System.out.println("文件不存在,创建文件失败!");
                    return;
                } else {
                    System.out.println("文件不存在,创建文件成功!");
                }
            }
            System.out.println("待写入Base64字符串的文件为:" + f1.getAbsolutePath());
            System.out.println("待写入Base64字符串的文件大小(字节):" + content.getBytes(StandardCharsets.UTF_8).length);
            out = new FileOutputStream(f1);
            bw = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
            bw.write(content);
            bw.flush();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally {
            try {
                if (null != out) {
                    out.close();
                }
                if (null != bw) {
                    bw.close();
                }
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }

    }

    /**
     * 将文件转换为base64字符串
     * @param imgPath
     * @return
     */
    public static String convertFileToBase64(String filePath) {
        byte[] data = null;
        InputStream in = null;
        // 读取文件字节数组
        try {
            in = new FileInputStream(filePath);
            System.out.println("待进行Base64转换文件为:" + new File(filePath).getAbsolutePath());
            System.out.println("待进行Base64转换文件大小(字节):" + in.available());
            data = new byte[in.available()];
            in.read(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                if (null != in) {
                    in.close();
                }
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
        // 对字节数组进行Base64编码,得到Base64编码的字符串
        Base64.Encoder encoder = Base64.getEncoder();
        String base64Str = encoder.encodeToString(data);
        return base64Str;
    }

    /**
     * 对字节数组字符串进行Base64解码并生成文件
     * 
     * @param fileStr      文件base64位数据
     * @param fileFilePath 保存文件全路径地址
     * @return
     */
    public static boolean generateBase64StringToFile(String fileStr, String fileFilePath) {
        OutputStream out = null;
        boolean flag = true;
        if (fileStr == null) // 文件base64位数据为空
            return false;
        try {
            File file = new File(fileFilePath);
            if (!file.exists()) {
                mkdirParents(file);
                if (!file.createNewFile()) {
                    System.out.println("文件不存在,创建文件失败!");
                    return false;
                } else {
                    System.out.println("文件不存在,创建文件成功!");
                }
            }
            Base64.Decoder decoder = Base64.getDecoder();
            // Base64解码
            byte[] b = decoder.decode(fileStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            out = new FileOutputStream(fileFilePath);
            out.write(b);
            out.flush();
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        } finally {
            try {
                if (null != out) {
                    out.close();
                }
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
        return flag;
    }

    /**
     * 判断文件的父级目录是否存在,不存在则创建
     * @param file 文件
     * @return true 父级目录存在或创建父级目录成功, false创建父级目录失败
     */
    private static boolean mkdirParents(File file){
        if (!file.getParentFile().exists()) {
            return file.getParentFile().mkdirs();
        }
        else {
            return true;
        }
    }

}


博客评论
还没有人评论,赶紧抢个沙发~
发表评论
说明:请文明发言,共建和谐网络,您的个人信息不会被公开显示。