Android 文件的存储和加载
生活随笔
收集整理的這篇文章主要介紹了
Android 文件的存储和加载
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Android 文件的存儲(chǔ)和加載,主要用于請(qǐng)求網(wǎng)絡(luò)中json文件的緩存,引入了一個(gè)簡(jiǎn)單的過期時(shí)間,供大家參考學(xué)習(xí)!
?
文件存儲(chǔ)
1 private void saveLocal(String json, int index) { 2 3 BufferedWriter bw = null; 4 try { 5 File dir=FileUtils.getCacheDir(); 6 //在第一行寫一個(gè)過期時(shí)間 7 File file = new File(dir, getKey()+"_" + index); // /mnt/sdcard/googlePlay/cache/home_0 8 FileWriter fw = new FileWriter(file); 9 bw = new BufferedWriter(fw); 10 bw.write(System.currentTimeMillis() + 1000 * 100 + ""); 11 bw.newLine();// 換行 12 bw.write(json);// 把整個(gè)json文件保存起來 13 bw.flush(); 14 bw.close(); 15 } catch (Exception e) { 16 e.printStackTrace(); 17 }finally{ 18 IOUtils.closeQuietly(bw); 19 } 20 }文件加載
1 private String loadLocal(int index) { 2 // 如果發(fā)現(xiàn)文件已經(jīng)過期了 就不要再去復(fù)用緩存了 3 File dir=FileUtils.getCacheDir();// 獲取緩存所在的文件夾 4 File file = new File(dir, getKey()+"_" + index); 5 try { 6 FileReader fr=new FileReader(file); 7 BufferedReader br=new BufferedReader(fr); 8 long outOfDate = Long.parseLong(br.readLine()); 9 if(System.currentTimeMillis()>outOfDate){ 10 return null; 11 }else{ 12 String str=null; 13 StringWriter sw=new StringWriter(); 14 while((str=br.readLine())!=null){ 15 16 sw.write(str); 17 } 18 return sw.toString(); 19 } 20 21 } catch (Exception e) { 22 e.printStackTrace(); 23 return null; 24 } 25 }?
轉(zhuǎn)載于:https://www.cnblogs.com/lude313/p/4796970.html
總結(jié)
以上是生活随笔為你收集整理的Android 文件的存储和加载的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Unix文件权限
- 下一篇: ICSharpCode.SharpZip