回顾数据存储(读、写)

数据存储(读、写)
1.分类
    1.共享参数存储
    2.file存储 内部存储和外部存储(sd卡)
    3.数据库存储
    4.内容提供者ContextProvider
    5.网络存储
2.共享参数存储   Shared Preferences
    1.特征
        1.存放轻量级的数据的存储方式
        2.本质上是以xml的格式存在的,通过键值对的方式对数据进行读取
        3.通常用于存储简单的数据信息
        4.应用程序卸载后,文件也会被删除
    2.存储数据的类型
   boolean int string  long float
    3.存放数据的路径
    4.存储数据
    5.读取数据
  
  
  1. package com.qf.day42_01;
  2. import android.app.Activity;
  3. import android.content.Context;
  4. import android.content.SharedPreferences;
  5. import android.content.SharedPreferences.Editor;
  6. import android.graphics.Color;
  7. import android.os.Bundle;
  8. import android.view.View;
  9. import android.widget.TextView;
  10. import android.widget.Toast;
  11. public class MainActivity extends Activity {
  12. private TextView tv;
  13. private SharedPreferences sp;
  14. @Override
  15. protected void onCreate(Bundle savedInstanceState) {
  16. super.onCreate(savedInstanceState);
  17. setContentView(R.layout.activity_main);
  18. tv = (TextView) findViewById(R.id.tv);
  19. sp = getSharedPreferences("MySet", Context.MODE_PRIVATE);
  20. }
  21. //共享参数存储数据
  22. public void write(View v){
  23. //得到共享参数对象
  24. //getPreferences(mode) 文件名称会以当前activity的类名来命名 这个也可以使用
  25. //name 文件的名称,不需要拓展名
  26. //mode 文件操作模式
  27. //(context.MODE_PRIVATE 文件只能被当前的应用程序访问,覆盖的模式,替换掉之前的内容,写入时如key相同则value值会覆盖之前的内容)
  28. //
  29. //得到编辑对象
  30. Editor editor = sp.edit();
  31. //向共享参数中写入数据
  32. editor.putString("msg", "你已经更改了TextView的设置");
  33. editor.putInt("color", Color.RED);
  34. editor.putInt("fontSize", 25);
  35. //提交数据
  36. editor.commit();
  37. Toast.makeText(this, "succes",1).show();
  38. }
  39. //以共享参数读取数据
  40. public void read(View v){
  41. //得到共享参数的对象
  42. String msg = sp.getString("msg","读取数据失败");
  43. int color = sp.getInt("color", 0);
  44. int fontSize = sp.getInt("fontSize", 20);
  45. //读取数据
  46. tv.setText(msg);
  47. tv.setTextColor(color);
  48. tv.setTextSize(fontSize);
  49. }
  50. }
实现记住密码登录
   
   
  1. package com.qf.day42_02;
  2. import android.app.Activity;
  3. import android.content.Context;
  4. import android.content.SharedPreferences;
  5. import android.content.SharedPreferences.Editor;
  6. import android.os.Bundle;
  7. import android.view.View;
  8. import android.widget.ArrayAdapter;
  9. import android.widget.CheckBox;
  10. import android.widget.EditText;
  11. import android.widget.Toast;
  12. public class MainActivity extends Activity {
  13. private CheckBox cb;
  14. private EditText pwd;
  15. private EditText user;
  16. private SharedPreferences sp;
  17. @Override
  18. protected void onCreate(Bundle savedInstanceState) {
  19. super.onCreate(savedInstanceState);
  20. setContentView(R.layout.activity_main);
  21. user = (EditText) findViewById(R.id.user);
  22. pwd = (EditText) findViewById(R.id.pwd);
  23. cb = (CheckBox) findViewById(R.id.cb);
  24. sp = getSharedPreferences("Login", Context.MODE_PRIVATE);
  25. // ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, resource)
  26. if (!"".equals(sp.getString("pwd", ""))&!"".equals(sp.getString("user", ""))) {
  27. user.setText(sp.getString("user", ""));
  28. pwd.setText(sp.getString("pwd", ""));
  29. cb.setChecked(true);
  30. }else {
  31. user.setText("");
  32. pwd.setText("");
  33. }
  34. }
  35. public void submit(View v){
  36. if (cb.isChecked()) {
  37. Editor editor = sp.edit();
  38. editor.putString("user", user.getText().toString().trim());
  39. editor.putString("pwd", pwd.getText().toString().trim());
  40. editor.commit();
  41. }else {
  42. Editor editor = sp.edit();
  43. editor.clear();
  44. editor.commit();
  45. }
  46. }
  47. }
3.file 存储
        内部存储  Internal Storage
        1.特点
                文件只能被当前应用程序访问,其他应用程序不能访问
                应用程序卸载后 内部存储文件也会被删除
        2.路径

        3.核心代码  FileOutPutStream    |    FileInputStream
                1.存入数据
                2.读取数据
        
  
  
  1. package com.qf.day42_03;
  2. import java.io.FileInputStream;
  3. import java.io.FileOutputStream;
  4. import android.app.Activity;
  5. import android.app.AlertDialog;
  6. import android.content.Context;
  7. import android.content.DialogInterface;
  8. import android.content.DialogInterface.OnClickListener;
  9. import android.os.Bundle;
  10. import android.view.Menu;
  11. import android.view.MenuItem;
  12. import android.view.View;
  13. import android.widget.ArrayAdapter;
  14. import android.widget.EditText;
  15. import android.widget.Toast;
  16. public class MainActivity extends Activity {
  17. private EditText ed1;
  18. private EditText ed2;
  19. private AlertDialog.Builder builder;
  20. private ArrayAdapter<String> adapter;
  21. @Override
  22. protected void onCreate(Bundle savedInstanceState) {
  23. super.onCreate(savedInstanceState);
  24. setContentView(R.layout.activity_main);
  25. ed1 = (EditText) findViewById(R.id.ed1);
  26. ed2 = (EditText)findViewById(R.id.et2);
  27. init();
  28. }
  29. public void write(View v){
  30. //得到输入框的内容
  31. String fileName = ed1.getText().toString().trim();
  32. String content = ed2.getText().toString().trim();
  33. //存入数据
  34. //打开内部文件存储的输出流
  35. //写入数据
  36. //关闭流
  37. try {
  38. FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);//第一个参数文件名称第二个参数模式
  39. fos.write(content.getBytes());
  40. fos.flush();
  41. fos.close();
  42. Toast.makeText(MainActivity.this, "success", 1).show();
  43. } catch (Exception e) {
  44. e.printStackTrace();
  45. }
  46. }
  47. public void read(View v){
  48. String fileName = ed1.getText().toString().trim();
  49. try {
  50. FileInputStream fis = openFileInput(fileName);
  51. byte[] buf = new byte[fis.available()];
  52. fis.read(buf);
  53. fis.close();
  54. ed2.setText(new String(buf));
  55. } catch (Exception e) {
  56. // TODO Auto-generated catch block
  57. e.printStackTrace();
  58. }
  59. }
  60. @Override
  61. public boolean onCreateOptionsMenu(Menu menu) {
  62. // TODO Auto-generated method stub
  63. getMenuInflater().inflate(R.menu.main, menu);
  64. return super.onCreateOptionsMenu(menu);
  65. }
  66. @Override
  67. public boolean onOptionsItemSelected(MenuItem item) {
  68. // TODO Auto-generated method stub
  69. switch (item.getItemId()) {
  70. case R.id.action_select:
  71. //获取内部存储中所有的文件名称
  72. String[] data = fileList();
  73. adapter.clear();
  74. adapter.addAll(data);
  75. //删除某个指定的文件deleteFile(name)
  76. //获得一个文件路径getFilesDir()
  77. adapter.notifyDataSetChanged();
  78. builder.show();
  79. break;
  80. }
  81. return super.onOptionsItemSelected(item);
  82. }
  83. public void init(){
  84. builder = new AlertDialog.Builder(MainActivity.this);
  85. builder.setIcon(R.drawable.ic_launcher);
  86. builder.setTitle("请选择文件名称");
  87. adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1);
  88. builder.setAdapter(adapter, new OnClickListener() {
  89. @Override
  90. public void onClick(DialogInterface dialog, int which) {
  91. // TODO Auto-generated method stub
  92. //将选中的文件名称设置到文件名的输入框中
  93. String fileName = adapter.getItem(which);
  94. ed1.setText(fileName);
  95. //设置点击事件
  96. read(null);
  97. }
  98. });
  99. }
  100. }
 
   4.外部存储 External Storage【SD卡存储】
            1.特点
                    1.插入sd卡
                    2.目录结构分为两部分:sd卡的公共目录、sd卡的私有目录        公共目录内的文件其他程序也可以访问,当程序卸载后公共目录中的文件不会删除。 私有目录下的文件只有本程序才能使用,私有目录下的文件会被清除。
            2.路径
                        mut/sdcard        4.0    之前的目录
                        storage/sdcard   4.0     之后的目录    公共目录
                        storage/sdcard/Android/data/应用程序包名...私有目录
            3.读写sd卡权限
                        WRITE_EXTERNAL_STORAGE        写权限
                        READ_EXTERNAL_STORAGE         读权限
            4.获取一下扩展卡的目录
                        getDownloadCacheDirectory()       下载目录中的缓存目录
                        getExternalStorageDirectory()      获取拓展卡的根目录 
            5.获取当前拓展卡的状态
                        getExternalStorageState()         得到拓展卡的状态         MEDIA_MOUNTED   已经被装载好可以使用的状态(挂载的状态)   判断存储的状态符合这个条件那么可以存取文件
  
  
  1. package com.qf.day42_04.tools;
  2. import java.io.BufferedReader;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.io.InputStreamReader;
  8. import android.content.Context;
  9. import android.graphics.Bitmap;
  10. import android.graphics.BitmapFactory;
  11. import android.os.Build;
  12. import android.os.Environment;
  13. import android.os.StatFs;
  14. public class SDCardUtils {
  15. //保存图片的目录
  16. private static final String PATH = Environment.getExternalStorageDirectory()+"/1614/img/";
  17. public static boolean isMounted(){
  18. //得到当前sd卡的状态
  19. String state = Environment.getExternalStorageState();
  20. //跟系统提供的挂载状态进行比较
  21. return state.equals(Environment.MEDIA_MOUNTED);
  22. }
  23. public static String getfileName(String path){
  24. return path.substring(path.lastIndexOf("/")+1);
  25. }
  26. /**
  27. * 保持到sd卡的公共目录中
  28. * @param path 用于截取图片名称
  29. * @param data 图片内容
  30. */
  31. public static void saveImg(String path,byte[] data){
  32. //判断sd卡是否可以使用
  33. //判断当前缓存的目录是否存在
  34. //将图片的字节写入到指定的文件中
  35. if (isMounted()) {
  36. File dir = new File(PATH);
  37. if (!dir.exists()) {
  38. dir.mkdirs();//级联创建
  39. }
  40. try {
  41. FileOutputStream fos = new FileOutputStream(new File(dir,getfileName(path)));
  42. fos.write(data);
  43. fos.flush();
  44. fos.close();
  45. } catch (Exception e) {
  46. // TODO Auto-generated catch block
  47. e.printStackTrace();
  48. }
  49. }else {
  50. return;
  51. }
  52. }
  53. /**
  54. * 根据图片的名称,从sd卡的公共目录中读取图片
  55. * @param path
  56. * @return
  57. */
  58. public static Bitmap getBitmap(String path){
  59. if (isMounted()) {
  60. File file = new File(PATH, getfileName(path));
  61. if (file.exists()) {
  62. //把绝对路径的图片转成bitmap
  63. return BitmapFactory.decodeFile(file.getAbsolutePath());
  64. }
  65. return null;
  66. }else {
  67. return null;
  68. }
  69. }
  70. public static void savePrivate(Context context,String fileName,String content){
  71. if (isMounted()) {
  72. //sd卡的私有目录 Environment.DIRECTORY_DOWNLOADS
  73. File file = new File(context.getExternalFilesDir(null), fileName);
  74. FileOutputStream fos = null;
  75. try {
  76. fos = new FileOutputStream(file);
  77. fos.write(content.getBytes());
  78. } catch (Exception e) {
  79. // TODO Auto-generated catch block
  80. e.printStackTrace();
  81. }finally{
  82. try {
  83. if (fos!=null) {
  84. fos.close();
  85. }
  86. } catch (IOException e) {
  87. // TODO Auto-generated catch block
  88. e.printStackTrace();
  89. }
  90. }
  91. }else {
  92. return;
  93. }
  94. }
  95. public static String openPrivate(Context context,String fileName){
  96. if (isMounted()) {
  97. String result = null;
  98. File file = new File(context.getExternalFilesDir(null), fileName);
  99. FileInputStream fis = null;
  100. BufferedReader reader = null;
  101. String line = null;
  102. StringBuilder sBuilder = new StringBuilder();
  103. try {
  104. fis = new FileInputStream(file);
  105. reader = new BufferedReader(new InputStreamReader(fis));
  106. while((line = reader.readLine())!=null){
  107. sBuilder.append(line);
  108. }
  109. result = sBuilder.toString();
  110. return result;
  111. } catch (Exception e) {
  112. // TODO Auto-generated catch block
  113. e.printStackTrace();
  114. }finally{
  115. if (fis!=null) {
  116. try {
  117. fis.close();
  118. } catch (IOException e) {
  119. // TODO Auto-generated catch block
  120. e.printStackTrace();
  121. }
  122. }if (reader!=null) {
  123. try {
  124. reader.close();
  125. } catch (IOException e) {
  126. // TODO Auto-generated catch block
  127. e.printStackTrace();
  128. }
  129. }
  130. }
  131. }else {
  132. return null;
  133. }
  134. return null;
  135. }
  136. //清除sd卡指定目录下的数据
  137. public static void clearCardCaches(){
  138. if (isMounted()) {
  139. //得到缓存目录中的文件
  140. File file = new File(PATH);
  141. if (file.exists()) {
  142. //列出指定目录中的所有文件
  143. File[] files = file.listFiles();
  144. for (int i = 0; i < files.length; i++) {
  145. files[i].delete();
  146. }
  147. }
  148. }else {
  149. return;
  150. }
  151. }
  152. //判断sd卡的可用空间
  153. public static boolean isAvailable(){
  154. if (isAvailable()) {
  155. //实例化文件管理系统的状态对象 StatFs
  156. StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
  157. long size = 0; //字节为单位的
  158. if (Build.VERSION.SDK_INT>=18) {
  159. size = statFs.getFreeBytes();
  160. }else {
  161. //计算可用的代码块*每个块的大小
  162. size = statFs.getFreeBlocks()*statFs.getBlockSize();
  163. }
  164. //sd卡的可用空间必须大于10M 则表示可以使用
  165. if (size>1*1024*1024*10) {
  166. return true;
  167. }else {
  168. return false;
  169. }
  170. }else {
  171. return false;
  172. }
  173. }
  174. }

    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值