美文网首页
持久化存储学习

持久化存储学习

作者: Crane_FeiE | 来源:发表于2018-09-12 07:59 被阅读0次

    文件存储

    1.写文件

    操作顺序:

    • 通过openFileOutput(String name, int mode)方法来新建一个FileOutputStream对象
    • 通过FileOutputStream对象作为OutputStreamWriter的构造方法的参数,构造OutputStreamWriter对象
    • 通过OutputStreamWriter对象作为BufferedWriter的构造方法的参数,构造BufferedWriter对象
    • 调用BufferedWriterwrite(String input)方法将字符串写入文件
        public void saveToFile(String input, Context context) {
            FileOutputStream fos = null;
            BufferedWriter writer = null;
            try {
                fos = context.openFileOutput("data", Context.MODE_PRIVATE);
                writer = new BufferedWriter(new OutputStreamWriter(fos));
                writer.write(input);
    
            }catch (IOException e){
                e.getMessage();
            } finally {
                try {
                    if(writer != null){
                        writer.close();
                    }
                } catch (IOException e){
                    e.getMessage();
                }
            }
        }
    

    2.读文件

    与写文件的过程类似,但是读取的时候是调用readLine()方法来逐行读取

        public void loadFile(Context context){
            FileInputStream fis = null;
            BufferedReader br = null;
            StringBuilder sb = new StringBuilder();
            try {
                fis = context.openFileInput("data");
                br = new BufferedReader(new InputStreamReader(fis));
                String line = "";
                while ((line = br.readLine()) != null){
                    sb.append(line);
                }
            }catch (IOException e){
                e.getMessage();
            }finally {
                try{
                    if(br != null){
                        br.close();
                    }
                } catch (IOException e){
                    e.getMessage();
                }
            }
        }
    



    SharedPreferences 存储读取

    SP的存储读取十分简单,在android的存储方式是一个xml的键值对结构的文件,android已经封装好了接口

        public void spSaveAndLoad(Context context){
            //get SP named "data"
            SharedPreferences sp = context.getSharedPreferences("data", Context.MODE_PRIVATE);
            //load a value from key, second param is for a default value.
            sp.getString("key", "");
            
            //save a value into key, use apply() or commit() at last to finally save your value
            sp.edit().putString("key", "value").apply();
        }
    }
    



    数据库操作

    1. 创建数据库

    复写SQLLiteOpenHelper抽象类提供的接口:

    public class MyLibraryDBHelper extends SQLiteOpenHelper {
        public static final String CREATE_BOOK = "create table Book ("
                + "id interger primary key autoincrement, "
                + "author text, "
                + "price real, "
                + "pages integer, "
                + "name text)";
        
        private Context mContext;
        
        public MyLibraryDBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);
            mContext = context;
        }
    
        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(CREATE_BOOK);
            
        }
    
        /**when using getWritableDatabase(), you should update your db version number into a higher version
         *
         */
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("drop table if exists BOOK");
            onCreate(db);
        }
    }
    

    2.增删查改

        private void queryDB(SQLiteDatabase db) {
            Cursor c = db.query("Book",null, null, null, null, null, null);
            while (c.moveToNext()){
                String name = c.getString(c.getColumnIndex("name"));
            }
            c.close();
        }
    
        private void insertToDB(SQLiteDatabase db) {
            ContentValues values = new ContentValues();
            values.put("name", "Oliver Twist");
            values.put("author", "Dickens");
            values.put("pages", 100);
            values.put("price", 50);
            db.insert("Book", null, values);
        }
    
        private void updateDB(SQLiteDatabase db) {
            ContentValues values = new ContentValues();
            values.put("price", 99);
            db.update("Book", values, "name = ?", new String[]{"Oliver Twist"});
        }
    
        private void deleteFromDB(SQLiteDatabase db) {
            db.delete("Book", "name = ?", new String[]{"Oliver Twist"});
        }
    

    🤔️疑问

    • 为什么数据库没用使用contentProvider封装?
    • 数据库操作不应在主进程中进行

    相关文章

      网友评论

          本文标题:持久化存储学习

          本文链接:https://www.haomeiwen.com/subject/ohqmgftx.html