• Android的四种储存方式(SQLite、FileSystem、SDCardSystem、SharedPreferences)


    主要记录一下安卓中几种常用的存储方式的用法。

    一、SQLite

      1、创建SQLiteOpenHelper对象(当然SQLiteOpenHelper是抽象类,不能直接创建);

      2、通过上面创建的对象调用getWritableDatabase()方法获取SQLiteDatabase对象;

      3、通过SQLiteDatabase对象就可以操作数据库了。

    • 创建一个类继承自SQLiteOpenHelper
      import android.content.Context;
      import android.database.sqlite.SQLiteDatabase;
      import android.database.sqlite.SQLiteDatabase.CursorFactory;
      import android.database.sqlite.SQLiteOpenHelper;
      
      public class DBHelper extends SQLiteOpenHelper {
      
          private final static String TABLE_NAME="sun";//表名
          
          public DBHelper(Context context, String name, CursorFactory factory, int version) {
              super(context, name, factory, version);
          }
      
          @Override
          public void onCreate(SQLiteDatabase db) {
              String  sql = "create table if not exists " + TABLE_NAME+"(id integer primary key autoincrement,sunValue varchar,Date  integer)";
              db.execSQL(sql);
          }
      
          @Override
          public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
              String sql = "drop table if exists "+ TABLE_NAME;
              db.execSQL(sql);
              onCreate(db);
          }
      
      }

      注意:至少需要创建一个构造方法并调用super方法,并覆写两个方法,第一个方法onCreate创建数据库时调用,第二个方法onUpgrade版本更新时调用。

    • 这时可以创建SQLiteOpenHelper对象并调用getWritableDatabase()方法获取SQLiteDatabase对象
              DBHelper dbHelper = new DBHelper(MainActivity.this, "db_Sun.db", null, 1);
              SQLiteDatabase db = dbHelper.getWritableDatabase();

      注意:db_Sun.db是要创建的数据库名

    • 获取到SQLiteDatabase对象就可操作数据库了,如 :插入一条数据
               String sql = "insert into sun(sunValue,Date) values('"+value+"',"+new Date().getTime()+") ";
               db.execSQL(sql);
    • 查询数据库中最新的一条数据(根据时间戳排序查询)
              Cursor c = db.rawQuery("select * from sun order by Date desc limit 1", null);
              c.moveToFirst();/*************************************/
              while (!c.isAfterLast()) {/*************************************/
                  String sunValue = c.getString(c.getColumnIndex("sunValue"));
                  long date = c.getLong(c.getColumnIndex("Date"));
                  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                  Date date2 = new Date(date);
                  
                  Log.i(TAG, sunValue+"--"+sdf.format(date2));
                  recv_tv.setText(sunValue);
                  c.moveToNext();/**************************************/
              }
              c.close();/**************************************/

    二、FileSystem

      其实就是文件的读存

      1、创建File对象      java.io.File.File(File dir, String name) 

      2、获取输出流/输入流   

          java.io.FileOutputStream.FileOutputStream(File file, boolean append) throws FileNotFoundException

             java.io.FileInputStream.FileInputStream(File file) throws FileNotFoundException

       3、写入或读取

       4、关闭流

    • 下面是一个完整FileSystemStorage的例子(其中Context为上下文,如:MainActivity.this)
      package file;
      
      import java.io.BufferedReader;
      import java.io.File;
      import java.io.FileInputStream;
      import java.io.FileOutputStream;
      import java.io.FileReader;
      import java.io.IOException;
      
      import android.content.Context;
      
      public class FileOperation {
      
          private FileInputStream fis;// 输入流
          private FileOutputStream fos;// 输出流
          private final String FILENAME = "fileContent.txt";
          private Context context;
      
          public FileOperation(Context context) {
              super();
              this.context = context;
          }
      
          /**
           * 读取系统文件写入的内容
           * 
           * @return
           * @throws IOException
           */
          public String readFileContent() throws IOException {
      
              String filecontent = null;
      
              File file = new File(context.getFilesDir(), FILENAME);
              fis = new FileInputStream(file);
      
              filecontent = readFis(fis);
      
              // System.out.println("readFileContent="+filecontent);
              return filecontent;
          }
      
          /**
           * 把输入流里面的内容读取到字节数组中
           * 
           * @param fis
           *            输入流
           * @throws IOException
           */
          private String readFis(FileInputStream fis) throws IOException {
      
              // 定义缓冲区
              byte[] buf = new byte[1024];
      
              int len = -1;
      
              StringBuilder sb = new StringBuilder();
      
              // 循环读取fis中的数据
              while ((len = fis.read(buf)) != -1) {
                  sb.append(new String(buf, 0, len));
              }
              // System.out.println("readFis="+sb.toString());
              return sb.toString();
          }
      
          /**
           * 读取文件的最后一行数据
           * 
           * @return
           */
          public String readFisLastLine() {
              File file = new File(context.getFilesDir(), FILENAME);
              String lastLine = null;
              String buf = null;
              BufferedReader br = null;
              try {
                  br = new BufferedReader(new FileReader(file));
                  if (file.length() > 1024 * 1024 * 1024) {
                      br.skip(file.length() / 3 * 2);//  当文件超过1M大小的时候,跳过文本长度的2/3,具体跳过多少视实际情况而定,文件越大可以跳过的部分越多
                  }
                  while ((buf = br.readLine()) != null && buf != "
      ") {
                      lastLine = buf;
                  }
                  br.close();
              } catch (IOException e) {
                  if (br != null) {
                      try {
                          br.close();
                      } catch (IOException e1) {
                          e1.printStackTrace();
                      }
                  }
                  e.printStackTrace();
              }
      
              return lastLine;
          }
      
          /**
           * 写入文件
           * 
           * @param content
           * @throws IOException
           */
          public void writeContent(String filecontent) throws IOException {
              // 通过传入的文件获得fos,默认为MODE_PRIVATE覆写
              File file = new File(context.getFilesDir(), FILENAME);
              if (false == file.exists()) {
                  file.createNewFile();
                  filecontent = "数据                              " + "时间" + "
      " + filecontent;// 加个列名
              }
      
              fos = new FileOutputStream(file, true);// 追加
              // fos=openFileOutput(FILENAME, MODE_PRIVATE);
      
              // 向fos写入文件内容
              fos.write(filecontent.getBytes());
              // 刷新
              fos.flush();
      
              // 关闭流,释放资源
              fos.close();
          }
      }

    三、SDCardSystem

      这和filesystem差不多,只是文件位置不同

    • 文件写入方法
      /**
           * 写入内容
           */
          protected void writeContent(String content) {
              /**
               * 检查SDCard的挂载(插入)状态
               */
              String sdCardState = Environment.getExternalStorageState();
              Log.i("state", sdCardState);
              /**
               * 把获取到的sdCard状态,进行判断是否挂载
               */
              if (sdCardState.equals(Environment.MEDIA_MOUNTED)) {// SDCard已挂载
                  File file = new File(Environment.getExternalStorageDirectory(), FILENAME);
                  Log.i("文件路径:", Environment.getExternalStorageDirectory().getAbsolutePath());
                  try {
                      fos = new FileOutputStream(file);
                      fos.write(content.getBytes());
                      fos.flush();
                      fos.close();
                  } catch (FileNotFoundException e) {
                      e.printStackTrace();
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
      
              }
          }
    • 文件读取方法
      /**
           * 读取SDCard文件的方法
           */
      
          protected String readSdCardFile() {
              /**
               * 获取并判断SDCard挂载状态
               */
              if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                  // SDCard已挂载
                  File file = new File(Environment.getExternalStorageDirectory(), FILENAME);
                  try {
                      fis = new FileInputStream(file);
                      content = readFis(fis);
                  } catch (FileNotFoundException e) {
                      e.printStackTrace();
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
              }
              return content;
          }
      
          private String readFis(FileInputStream fis) throws IOException {
              byte[] buf = new byte[1024];
              int len = -1;
              StringBuilder sb = new StringBuilder();
              while ((len = fis.read(buf)) != -1) {// 循环读取fis中的数据
                  sb.append(new String(buf, 0, len));
              }
              // 关闭流
              fis.close();
      
              return sb.toString();
          }

    四、SharedPreferences(喜好.xml文件存储)

      SharedPreferences文件是一个xml文件,保存的是键值对(key-value)。

      1、通过上下文SharedPreferences对象;

      2、获取Editor;

      3、put值;

      4、提交。

    • 完整的存储读取类
      package file;
      
      import java.util.Map;
      import android.content.Context;
      import android.content.SharedPreferences;
      import android.content.SharedPreferences.Editor;
      
      
      public class FileOperation {
      
          private final String SPNAME = "fileContent";// 喜好文件名
          private Context context;
          private SharedPreferences sp;
      
          public FileOperation(Context context) {
              super();
              this.context = context;
          }
      
      
          /**
           * 读取系统文件写入的内容(这里读取最后一条)
           * @return
           */
          public  String readFileContent()  {
              sp = context.getSharedPreferences(SPNAME, Context.MODE_PRIVATE);
      //        sp.getString(key, defValue);//通过key获取一个value
              
              Map<String, ?> map =  sp.getAll();
      /*        for (Entry<String, String> entry : map.entrySet()) {//遍历所有的key-value
                    
                  System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());  
                
              } */
      
              String lastKey = null;
              String lastValue = null;
              for (String key : map.keySet()) {//遍历所有的Key,得到最后一个key  
                  lastKey = key;
              }
              if (null != lastKey) {
                  lastValue = (String) map.get(lastKey);//获取最后一个value
      //            lastValue = sp.getString(lastKey, "");
              }
              return lastValue;
              
          }
      
          /**
           * 写入文件
           * 
           */
          public  void writeContent(String key,String value) {
              /*
               * sp=MainActivity.this.getPreferences(mode);
               * 这种方式获取的喜好文件一个Activity有且仅有一个 原因是:它得到的喜好文件的文件名为这个Activity的类名
               */
      
              // 通过上下文获取sp
              sp = context.getSharedPreferences(SPNAME, Context.MODE_PRIVATE);
               // 获取editor
               Editor editor=sp.edit();
               //放入键值对
               editor.putString(key, value);
              
               //注意:放入键值对后一定要提交
               editor.commit();
          }
      }

    小结:

    SQLite、FileSystem、SharedPreferences方式的文件储存的位置都在根目录下data目录下的data目录下的当前包名下:/data/data/com.yyc.test/...

    SDCardSystem方式的存储位置在sd卡中(我手机没有sd卡,不知道为什么直接在根目录下,欢迎右上角QQ交流)

  • 相关阅读:
    Jenkins调用selenium找不到webdriver:selenium.common.exceptions.WebDriverException: Message: unknown error: cannot find Chrome binary
    列表的基本操作
    jenkins集成发送测试报告的常见问题解决
    Chrome 浏览器前端调试技巧大揭秘
    搭建Redis三主三从集群
    Jenkins安装
    python中hasattr()、getattr()、setattr()函数的使用
    python单元测试之unittest框架
    python环境配置详细步骤
    Android:EditText 设置弹出数字输入法键盘
  • 原文地址:https://www.cnblogs.com/hyyq/p/7683937.html
Copyright © 2020-2023  润新知