Android 根据文件路径base64字符串和文件互相转换

android 本地存文件,通过base64转码文件存储到本地

  1. 根据版本获取文件管理目录 API 29之后需要按下方的方法获取文件路径
    public static String getSDPath(Context context){
        String path = "";
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.Q){
            path =context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).toString() + "/intelligentKit";
        }else{
            path = Environment.getExternalStorageDirectory().toString() + "/intelligentKit";
        }
        return path;
    }

2.Base64字符串转文件
先通过BASE64Decoder 将base64字符串解码转为字节数组,在通过字节流将字节数组写入文件中,通过bytes.length 属性可查看base64字符串转字节是否有缺失,比对文件大小查看是否一样

//Base64字符串转为文件,base64为字符串,filaName为保存的文件名称,savePath为保存路径
//import sun.misc.BASE64Decoder;
//import sun.misc.BASE64Encoder;
    public static void base64ToFile(String base64, String fileName, String savePath) {
        //前台在用Ajax传base64值的时候会把base64中的+换成空格,所以需要替换回来。
        //有的后台传的数据还有image:content..., 转换的时候都需要替换掉,转换之前尽量把base64字符串检查一遍
        base64 = base64.replaceAll(" ", "+");

        File file = null;
        //创建文件目录
        String filePath = savePath;
        File dir = new File(filePath);
        if (!dir.exists()) {
            boolean a = dir.mkdirs();
            Log.d(TAG, "base64ToFile: 文件不存在,创建"+a);
        }
        BASE64Decoder decoder = new BASE64Decoder();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        java.io.FileOutputStream fos = null;
        try {
            byte[] bytes = decoder.decodeBuffer(base64);//base64编码内容转换为字节数组
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bytes);
            bis = new BufferedInputStream(byteInputStream);
            Log.d(TAG, "base64ToFile: ${bytes}=="+bytes.length);

            file= new File(filePath +"/"+ fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);

            byte[] buffer = new byte[1024];
            int length = bis.read(buffer);
            while(length != -1){
                bos.write(buffer, 0, length);
                length = bis.read(buffer);
            }
            bos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

3.将文件转为Base64字符串
这个没什么可说的,跟上面的流程相反,通过字节流读文件,然后将读出的字节数组通过BASE64Encoder 编码

public static String PDFToBase64(File file) {
        BASE64Encoder encoder = new BASE64Encoder();
        FileInputStream fin =null;
        BufferedInputStream bin =null;
        ByteArrayOutputStream baos = null;
        BufferedOutputStream bout =null;
        try {
            fin = new FileInputStream(file);
            bin = new BufferedInputStream(fin);
            baos = new ByteArrayOutputStream();
            bout = new BufferedOutputStream(baos);
            byte[] buffer = new byte[1024];
            int len = bin.read(buffer);
            while(len != -1){
                bout.write(buffer, 0, len);
                len = bin.read(buffer);
            }
            //刷新此输出流并强制写出所有缓冲的输出字节
            bout.flush();
            byte[] bytes = baos.toByteArray();
            return encoder.encodeBuffer(bytes).trim();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                fin.close();
                bin.close();
                bout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 大家早上好! 由于心里承受能力差,需要住院治疗! 精神分裂症郁郁一发作好折磨人,一整个晚上睡不着,还害怕焦虑紧张,...
    a888e55ebc58阅读 803评论 0 0
  • 庆幸的是,我己经坚持了一个月了,早起的感觉真好。 但还是不能完全做到早睡,导致经常不能按时起来,本来计划5点多,这...
    文字先生阅读 952评论 0 0
  • 背景 使用git push命令上传代码到仓库时,因为项目中有10M的模型文件,最后出现如下错误: 根据错误信息应该...
    颈椎以上瘫痪阅读 4,332评论 0 0
  • 我早知这世间万物实在难及你分毫, 你就该端坐高堂上, 不要染尘埃, 所以我借起千江明月, 万古词赋, 于微薄的雪色...
    完颜茉阅读 3,493评论 0 3
  • 时光过得太快,喜欢的留不住,想要的太遥远。六月的风,七月的雨,来得匆匆,消失地无影无踪。
    浮生若梦ldx阅读 31评论 0 0