JAVA将任意文件转成BASE64编码和将BASE64编码再转换成文件

import cn.hutool.core.codec.Base64;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;

@Slf4j
public class CallableTest {

    /**
     * 将file文件转换成Byte数组
     * @param file 转换文件
     * @return Byte数组
     */
    public static byte[] getBytesByFile(File file) throws IOException {
        FileInputStream fis = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
        try {
            fis = new FileInputStream(file);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            byte[] data = bos.toByteArray();
            return data;
        } catch (Exception e) {
            log.error("将文件转换成Byte数组失败", e);
        } finally {
            if (fis != null){
                fis.close();
            }
            bos.close();
        }
        return null;
    }

    /**
     * @param bytes byte数组
     * @param fileRoute 文件路径
     * @param fileName 文件名
     */
    public static void upload(byte[] bytes,String fileRoute,String fileName) {
        try {
            File directory=new File(fileRoute);
            if (!directory.exists()){
                directory.mkdirs();
            }
            File file = new File(directory, fileName);
            BufferedOutputStream bos = new BufferedOutputStream(Files.newOutputStream(file.toPath()));
            bos.write(bytes);
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void test1() throws IOException {
        String path="C:\\Users\\Lenovo\\Desktop\\工作\\共产党宣言.pdf";
        File file=new File(path);
        byte[] bytes=getBytesByFile(file);
        String fileBase64=Base64.encode(bytes);
        System.out.println(fileBase64);
        upload(Base64.decode(fileBase64),"D://","共产党宣言.pdf");
    }

    public static void main(String[] args) throws IOException {
        test1();
    }
}

你可能感兴趣的:(java,jvm,开发语言)