持久化存储学习

文件存储

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封装?
  • 数据库操作不应在主进程中进行
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、基础知识:1、JVM、JRE和JDK的区别:JVM(Java Virtual Machine):java虚拟机...
    杀小贼阅读 2,459评论 0 4
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,817评论 25 709
  • 蓝色雪的秘密 沉默着雪的夜,安静着夜的歌。 一片泻过你眼神之色的雪,在路边一隅细数我的印辙 把梦的薄膜惊破,发现是...
    先明日辰阅读 221评论 0 1
  • 前言 虽然项目主体是原生Android开发,但是难免会遇到一些H5页面,如:首页Banner的活动推送。我们之所以...
    呱呱_阅读 1,669评论 0 2
  • 我希望我的人生能够写出美丽的篇章,我不吝惜一次次的修改,但我不能容忍自己每次都是在无用的修改标点符号。
    06d12fe83199阅读 162评论 0 0