分析
- 配置读写权限
- 写文件工具类,主要实现获得指定路径的字符串,例如缓存或图片文件夹
- 判断是否存在SD卡
- 如果有,则指定一条绝对路径,例如( path = /sd/ReadTest/”str”)
- 如果没有,则指定项目安装包下的缓存,例如(Paht = /data/data/项目安装包/cache)
- 根据指定路径与文件名称,构建读写文件
- 根据读写文件,构建读写文件流
- 根据读写文件流,读文件成字符串或写字符串到指定文件
配置
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
工具类
public class BaseApplication extends Application {
public static BaseApplication application;
@Override
public void onCreate() {
super.onCreate();
application = this;
}
public static BaseApplication getApplication(){
return application;
}
}
public class FileUtils {
private static String TAG = "ReadTest";
private static String CACHE = "cache";
public static String getDir(String str){
String path = "";
if (isSDAvail()){
String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
path += sdPath;
path += "/";
path += TAG;
path += "/";
path += str;
}else {
File cashe = ContextUtils.GetContext().getCacheDir();
path = cashe.getAbsolutePath();
}
File file = new File(path.toString());
if (! file.exists() || !file.isDirectory()){
file.mkdir();
}
return path;
}
public static boolean isSDAvail() {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
return true;
}
return false;
}
public static String getCacheDir(){
return getDir(CACHE);
}
}
读取Cache
private String loadCache(String url) {
String cashe = FileUtils.getCacheDir();
File dir = new File(cashe);
int i = url.lastIndexOf("/");
String fileName = url.substring(i, url.length());
File file = new File(dir, fileName);
BufferedReader br = null;
try {
FileReader fr = new FileReader(file);
br = new BufferedReader(fr);
String line = null;
StringBuffer sb = new StringBuffer();
while ((line = br.readLine()) != null){
sb.append(line);
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
写入Cache
private void saveCache(String url, String res) {
String cache = FileUtils.getCacheDir();
File dir = new File(cache);
int i = url.lastIndexOf("/");
String fileName = url.substring(i, url.length());
File file = new File(dir,fileName);
BufferedWriter bw = null;
try {
FileWriter fw = new FileWriter(file);
bw = new BufferedWriter(fw);
bw.write(res);
bw.flush();
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}