一.添加权限
<!--在SDCard中创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
二.保存文件
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
try {
String fileName = MD5Encoder.encode(key);
File file = new File(Environment.getExternalStorageDirectory()+"/xxx/file",fileName);
File parentFile = file.getParentFile();//mnt/sdcard/xxx/file
if(!parentFile.exists()){
//创建目录
parentFile.mkdirs();
}
if (!file.exists()){
file.createNewFile();
}
//保存文本数据
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(value.getBytes());
fileOutputStream.close();
}catch (Exception e){
e.printStackTrace();
LogUtil.e("本地缓存失败");
}
}
三.读取文件
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
try {
String fileName = MD5Encoder.encode(key);
File file = new File(Environment.getExternalStorageDirectory()+"/xxx/file",fileName);
if (file.exists()){
FileInputStream is = new FileInputStream(file);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer))!=-1){
stream.write(buffer,0,length);
}
String result = stream.toString();
is.close();
stream.close();
return result;
}
}catch (Exception e){
e.printStackTrace();
LogUtil.e("获取本地文件缓存失败");
}
}