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字符串解碼轉為字節(jié)數組,在通過字節(jié)流將字節(jié)數組寫入文件中,通過bytes.length 屬性可查看base64字符串轉字節(jié)是否有缺失,比對文件大小查看是否一樣
//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;
//創(chuàng)建文件目錄
String filePath = savePath;
File dir = new File(filePath);
if (!dir.exists()) {
boolean a = dir.mkdirs();
Log.d(TAG, "base64ToFile: 文件不存在,創(chuàng)建"+a);
}
BASE64Decoder decoder = new BASE64Decoder();
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
java.io.FileOutputStream fos = null;
try {
byte[] bytes = decoder.decodeBuffer(base64);//base64編碼內容轉換為字節(jié)數組
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字符串
這個沒什么可說的,跟上面的流程相反,通過字節(jié)流讀文件,然后將讀出的字節(jié)數組通過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);
}
//刷新此輸出流并強制寫出所有緩沖的輸出字節(jié)
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;
}