android 本地存文件,通过base64转码文件存储到本地
- 根据版本获取文件管理目录 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;
}