Android中的五种数据存储方式

这五种方式分别是:

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 block
e.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

2.MODE_APPEND = 32768
3.MODE_WORLD_READABLE = 1
4.MODE_WORLD_WRITEABLE = 2

MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容。
MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
MODE_WORLD_READABLE:表示当前文件可以被其他应用读取。
MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入。
 
  如果希望文件被其他应用读和写,可以传入: openFileOutput("itcast.txt",MODE_WORLD_READABLE + MODE_WORLD_WRITEABLE); android有一套自己的安全模型,当应用程序(.apk)在安装时系统就会分配给他一个userid,当该应用要去访问其他资源比如文件的时候,就需要userid匹配。默认情况下,任何应用创建的文件,sharedpreferences,数据库都应该是私有的(位于/data/data//files),其他程序无法访问。 除非在创建时指定了MODE_WORLD_READABLE或者MODE_WORLD_WRITEABLE ,只有这样其他程序才能正确访问。


-------封装成组件---------

这是使用的方式,单例模式
if(FileManager.getInitialize().isSdCardAvailable()){
			path = FileManager.getInitialize().getSDOrCache(this, "/ambow/asso/apk/");
		}
		else
			path = 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);
		else
			url = 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值