Android中数据存储和访问方式

Android中数据存储和访问方式一般有5种:

1,文件

2,SharedPreferences

3,SQLite数据库

4,ContentProvider

5,网络


一、文件

1-1,写入文件到手机

	private void writeFile(String filename){
		try {
			FileOutputStream  fos = this.openFileOutput(filename, Context.MODE_PRIVATE);
			fos.write("试验测试文件".getBytes());
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
1-2,从手机中读取文件

	private void readFile(String filename) {
		try {
			FileInputStream fis = this.openFileInput(filename);
			String content = readInStream(fis);
			Log.i("readFile", content);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String readInStream(FileInputStream inStream) {
		try {
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int length = -1;
			while ((length = inStream.read(buffer)) != -1) {
				// 0-起始位置,length-个数
				// 将buffer数组从下标0开始的length个字节数据写入到内存输出流中
				//下次循环存入时outStream中的字节数组下标增长一个length
				outStream.write(buffer, 0, length);
			}
			outStream.close();
			inStream.close();
			return outStream.toString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
2-1,写入文件到SDCard

注意:写文件到SDCard需要权限:

	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
	private void saveFileToSD(String content, String filename) {
		// 首先判断手机是否安装了SD卡
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			 File SdDir = Environment.getExternalStorageDirectory();
			
			 File file = new File(SdDir, filename);
			 FileOutputStream fos;
			 try {
			 fos = new FileOutputStream(file);
			 fos.write(content.getBytes());
			 fos.close();
			 } catch (Exception e) {
			 Log.i("SaveToSD", "fail");

			 }
		} else {
			Toast.makeText(this, "未安装SD卡", Toast.LENGTH_LONG).show();
		}
	}

二、SharedPreferences 用于对软件配置参数的保存,背后是使用的XML格式保存

1,写入到SharedPreferences数据

	private void saveToSP(String name, String password) {
		// 拿到一个SharedPreferences
		SharedPreferences sp = this.getSharedPreferences("config", Context.MODE_PRIVATE);
		//获取编辑器
		Editor editor = sp.edit();
		editor.putString("name", name);
		editor.putString("password", password);
		//提交修改
		editor.commit();
	}
2-1,从本应用的SharedPreferences中读取数据

	private Map<String,String> readFromSP() {
		// 
		SharedPreferences sp = this.getSharedPreferences("config",Context.MODE_PRIVATE);
		Map<String, String> map = (Map<String, String>) sp.getAll();
		return map;
	}
2-2,从其他应用的SharedPreferences中读取数据

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值