Android 数据存储(一)

Android数据存储

Android主要提供了三种数据存储的方式:文件存储、SharedPreferences和数据库存储

文件存储
  • Context类提供了一个方法openFileOutput():接收2个参数

    • 第一个参数是文件名,文件名不包含路径,因为所有的文件都默认存储到/data/data/<package name>/files/目录下
    • 第二个参数是操作模式,主要有两种:
      • MODE_PRIVATE :默认操作模式,文件名相同时,会进行覆盖
      • MODE_APPEND :文件名相同时,会追加内容,不存在就自动创建
    • 返回对象是FileOutputStream,可以通过Java流控制文件写入
  • Demo Code:

    借助openFileOutput()得到FileOutputStream对象,再通过OutputStreamWriter()得到BufferWriter对象就能直接写入文件了

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    public void save(){
    String data = "要存储的数据";
    FileOutputStream out = null;
    BufferedWriter writer = null;
    try{
    out = openFileOutput("文件名", Context.MODE_PRIVATE);
    writer = new BufferWriter(new OutputStreamWriter(out));
    writer.writer(data);
    }catch(IOException e){
    e.printStackTrace();
    }finally{
    try{
    if(writer != null){
    writer.close();
    }
    }catch(IOException e){
    e.printStackTrace();
    }
    }
    }
从文件中读取数据
  • Context类还提供了一个方法 openFileInput(): 接收一个参数

    • 只有一个参数,文件名,件名不包含路径,因为所有的文件都默认存储到/data/data/<package name>/files/目录下
    • 返回一个FileInputStream对象,通过java流读取数据
  • Demo code:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    public String load(){
    public String in = null;
    BufferedReader reader = null;
    StringBuilder content = new StringBuilder();
    try{
    in = openFileInput("要读取的文件名");
    reader = new BufferedReader(new InputStreamReader(in));
    String line = "";
    while((line = reader.readLine() != null){
    content.append(line);
    }
    }catch(IOException e){
    e.printStackTrace();
    }finally{
    if(reader != null){
    try{
    reader.close();
    }catch(IOException e){
    e.printStackTrace();
    }
    }
    }
    return content.toString();
    }
0%