工具篇——Base64FileUtil(将文件转成base64 字符串)

写代码的四点:
     1.明确需求。要做什么?
     2.分析思路。要怎么做?(1,2,3……)
     3.确定步骤。每一个思路要用到哪些语句、方法和对象。
     4.代码实现。用具体的语言代码将思路实现出来。

学习新技术的四点:
     1.该技术是什么?
     2.该技术有什么特点?(使用需注意的方面)
     3.该技术怎么使用?(写Demo)
     4.该技术什么时候用?(在Project中的使用场景 )

----------------------早计划,早准备,早完成。-------------------------

代码如下:
package com.wy.test.other;

import android.util.Base64;

import java.io.File;
import java.io.FileInputStream;

/**
 * encodeBase64File:(将文件转成base64 字符串)
 * 需要权限:<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
 * 用于向服务器上传图片
 */

public class Base64FileUtil {

    /**
     * encodeBase64File:(将文件转成base64 字符串).
     *
     * @param path 文件路径
     * @return Base64字符串
     * @throws Exception
     */
    public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return Base64.encodeToString(buffer, Base64.DEFAULT);
    }
}
在项目中的应用:

try {
    String encodeBase64File = Base64FileUtil.encodeBase64File("/storage/emulated/0/Pictures/Screenshots/Screenshot_2018-04-10-16-36-45.jpeg");
    LogUtil.e("encodeBase64File", encodeBase64File + "");
} catch (Exception e) {
    e.printStackTrace();
}

猜你喜欢

转载自blog.csdn.net/qq941263013/article/details/80166652