Android中的五种数据存储方式
来源:互联网 发布:西科软件科技有限公司 编辑:程序博客网 时间:2024/05/22 09:00
这五种方式分别是:
1、SharedPreferences(偏好设置),读取XML文件
2、文件存储
(1)assets(程序内部的资源,只能读)
(2)data/data/主包名/files目录下的,能读能写 || 手机内存
(3)读SD卡中的文件,需要申请权限
3、SQLite---->http://blog.csdn.net/u013519020/article/details/52229013
4、ContentProvider
5、网络流
一、SharedPreferences(偏好设置)本身不支持写,通过Editor获得写的能力
特点:轻量级存储,存放在XML文件中,采用Key--Value存取。
文件位置:data / data / 主包名 / shared_prefs / *.XML
编译器查找方式:Window-->Show View-->--other-->File Explorer(资源管理器)
存:(权限在后面还会有介绍)
Context ctx = MainActivity.this;//第一个参数是文件名,第二个是读写模式SharedPreferences sp=ctx.getSharedPreferences("t05", MODE_PRIVATE);//获得编译Editor editor = sp.edit();//存数据editor.putString("", "");editor.commit();取:
Context ctx = MainActivity.this;//第一个参数是文件名,第二个是读写模式SharedPreferences sp=ctx.getSharedPreferences("t05", MODE_PRIVATE);String s=sp.getString("key", "取不到值时的默认值");
----------------------------文件存储------------------------
A.assets(只读、不能修改或删除),这个是编译时存放的资源文件位置如图。
读取数据:
try {//创建流InputStream in = this.getAssets().open("文件名.扩展名");//读出数据Bitmap bm=BitmapFactory.decodeStream(in);in.close();in=null;} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}
B.读写数据(读写手机自身内存)
位置:data/data/主包名/files目录下的 || 也可以使用context.getFilesDir().getAbsolutePath()获得内存根路径
存:
try {OutputStream os=this.openFileOutput("文件名", MODE_PRIVATE);os.write("wa".getBytes());os.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}
取:
try {InputStream in=this.openFileInput("文件名");//缓冲区byte b[]=new byte[1024];//创建缓存ByteArrayBuffer ba=new ByteArrayBuffer(0);int l;//读while((l=in.read(b))>-1){ba.append(b,0,l);}//转化String s=new String(ba.toByteArray());} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}
C.SDCard读写文件
(一).首先要在AndroidManifest.XML中添加权限,两种方式添加:1.傻瓜式添加
打开这个清单文件-->Permissions-->Add-->Permission(创建权限)、Uses Permission(申请/使用权限)
Name中选择: android.permission.READ_EXTERNAL_STORAGE//写权限
android.permission.WRITE_EXTERNAL_STORAGE//读权限
android.permission.MOUNT_UNMOUNT_FILESYSTEMS//创建、删除
2.牛人式添加(手敲)
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
在manifest节点中添加
(二).判断SDCard是否存在
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
(三).得到SDCard路径
File dir = Environment.getExternalStorageDirectory();
....此处省略一万个字
(五).关闭流,关闭文件,关闭一切,赋null,注意顺序。
---------------------------权限介绍-----------------------------------
权限共有四种,来自于context:
1.MODE_PRIVATE = 0
if(FileManager.getInitialize().isSdCardAvailable()){path = FileManager.getInitialize().getSDOrCache(this, "/ambow/asso/apk/");}elsepath = FileManager.getInitialize().getSDOrCache(this, "");文件管理的组件
public class FileManager {private static FileManager manager;/** * 有效缓存时间是3天 */private static final long maxCacheTime = 1000*60*60*24*15;/** * 构造函数 * @param context */public FileManager(){}/** * 单例,获取FileManager实例 * @param context * @return */public static FileManager getInitialize(){if(manager == null)manager = new FileManager();return manager;}/** * 获取缓存cache目录路径 * @param context上下文 * @return */public String getCacheDir(Context context, String path){StringBuffer dir = new StringBuffer();dir.append(context.getFilesDir().getAbsolutePath());if(!path.startsWith("/"))dir.append("/");dir.append(path);File file = new File(dir.toString());if(!file.exists())file.mkdirs();return dir.toString();}/** * 获取sd卡缓存路径 * * @param path路径 * @return * 有sd卡的返回sd上的路径 * 没有sd卡返回null */public String getSDDir(String path){if(!isSdCardAvailable())return null;StringBuffer dir = new StringBuffer();dir.append(Environment.getExternalStorageDirectory());if(!path.startsWith("/"))dir.append("/");dir.append(path);File file = new File(dir.toString());if(!file.exists())file.mkdirs();return dir.toString();}/** * 获取缓存文件的路径 * @param path缓存文件的路径 * @param url保存的文件的url * @return */public String getCacheFileUrl(Context context,String path, String url){return getSDOrCache(context,path)+formatPath(url);}/** * 获取缓存路径 * @param context上下文 * @param path路径 * @return * 有sd卡返回sd上的路径 * 没有sd卡返回cach中的路径 */public String getSDOrCache(Context context, String path){String url = null;if(isSdCardAvailable())url = getSDDir(path);elseurl = getCacheDir(context, path);return url;}/** * 检测内存卡是否可用 * @return 可用则返回 true */public boolean isSdCardAvailable(){if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){return true;}return false;}/** * 格式化url地址 * 以便根据url来命名文件 * @param name图片url * @return */public String formatPath(String name){String path = name;path = path.replace(":", "_");path = path.replace("/", "_");return path;}/** * 判断该路径的文件是否存在 * @param path文件路径(完全路径) * @return */public boolean isExists(String path){File file = new File(path);if(file.exists())return true;return false;}/** * 判断当前目录是否存在文件 * @param path * @return */public boolean hasMoreFile(String path){File file = new File(path);if(!file.exists())return false;String[] files = file.list();if(files == null || files.length == 0)return false;return true;}/** * 清除sd卡中过期的缓存 * * @param basePath路径(要清楚文件的路径) */public void cleanInvalidCache(String basePath){File file = new File(basePath);if(!file.exists()) return;File[] caches = file.listFiles();if(caches == null || caches.length == 0) return;long now = System.currentTimeMillis();try {for(int i=0;i<caches.length;i++){if((now - caches[i].lastModified()) < maxCacheTime){continue;}caches[i].delete();try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();//每删除一张图片后停留10毫秒,防止cpu占用率过高,造成程序无响应}}} catch (Exception e) {e.printStackTrace();}}/** * 保存保存输入流 * @param path要保存的完全路径 * @param is网络获取的inputstream流 */public void saveInputStream(String path,InputStream is){if(!isExists(path)){File file = new File(path);FileOutputStream fos = null;try {fos = new FileOutputStream(file);int size = 0;byte[] buffer = new byte[1024];while((size = is.read(buffer)) != -1)fos.write(buffer, 0, size);fos.flush();fos.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally{try {if(fos != null){fos.close();fos = null;}if(file != null)file = null;} catch (IOException e) {e.printStackTrace();}}}}/** * 从文件中读取流 * @param path文件路径 * @return */public InputStream loadInputStream(String path){InputStream is = null;if(isExists(path)){File file = new File(path);try {is = new FileInputStream(file);} catch (FileNotFoundException e) {e.printStackTrace();return null;}}return is;}/** * 把对象写入文件 * * @throws Exception */public void WriteObject(Object obj,Context context,String path) throws Exception {FileOutputStream fis = context.openFileOutput(path, Context.MODE_PRIVATE);ObjectOutputStream oos = new ObjectOutputStream(fis);oos.writeObject(obj);oos.close();fis.close();}/** * 从文件读取对象 * * @return * @throws Exception */public Object readObject(Context context,String path) throws Exception {Object obj = new Object();FileInputStream fis = context.openFileInput(path);ObjectInputStream oos = new ObjectInputStream(fis);obj = oos.readObject();oos.close();fis.close();return obj;}/** * 删除保存文件 * @param path 文件的完整路径 */public void delete(String path){File file = new File(path);if(file.exists())file.delete();}}
转载请声明:http://blog.csdn.net/u013519020/article/details/52233421
- Android中的五种数据存储方式
- Android的五种数据存储方式
- Android五种数据存储方式
- Android五种数据存储方式
- android 五种数据存储方式
- android中五种数据存储方式
- Android五种数据存储方式
- Android的五种数据存储方式
- android五种数据存储方式
- Android中的5种数据存储方式
- Android中的5种数据存储方式。
- Android中的5种数据存储方式。
- Android中的5种数据存储方式
- Android中的5种数据存储方式
- Android中的5种数据存储方式
- Android中的5种数据存储方式
- Android中的5种数据存储方式
- android中的几种数据存储方式
- datagrid getSelections只能获取一行
- 降低Java垃圾回收开销的5条建议
- CodeForces 670D Triangles
- iOS时间那些事
- 关于Pods written in Swift can only be integrated as frameworks问题的解决
- Android中的五种数据存储方式
- javascript中的数组
- android 广播的方法
- Java开发者应当理解的专业术语
- hdoj 1179 Ollivanders: Makers of Fine Wands since 382 BC. (二分图--最大匹配)
- [BZOJ2436][Noi2011]Noi嘉年华(dp)
- 关于STM32 的 硬件IIC和 模拟IIC理解学习
- 百度搜索小尾巴
- linux下导入、导出mysql数据库命令