为了账号安全,请及时绑定邮箱和手机立即绑定

数据持久化之文件存储

标签:
Android

文件存储

         文件存储是 Android 中最基本的一种数据存储方式,它不对存储的内容进行任何的格式化处理,所有数据都是原封不动地保存到文件当中的,因而它比较适合用于存储一些简单的文本数据或二进制数据。如果你想使用文件存储的方式来保存一些较为复杂的文本数据,就需要定义一套自己的格式规范,这样方便于之后将数据从文件中重新解析出来。

将数据存储到文件中

         Context 类中提供了一个 openFileOutput ()方法,可以用于将数据存储到指定的文件中。这个方法接收两个参数,第一个参数是文件名,在文件创建的时候使用的就是这个名称,注意这里指定的文件名不可以包含路径,因为所有的文件都是默认存储到/data/data//files/ 目 录 下 的 。 第 二 个 参 数 是 文 件 的 操 作 模 式 , 主 要 有 两 种 模 式 可 选 ,MODE_PRIVATE 和 MODE_APPEND。其中 MODE_PRIVATE 是默认的操作模式,表示当指定同样文件名的时候,所写入的内容将会覆盖原文件中的内容,而 MODE_APPEND 则表示如果该文件已存在就往文件里面追加内容,不存在就创建新文件。 openFileOutput ()方法返回的是一个 FileOutputStream 对象,得到了这个对象之后就可以使用 Java 流的方式将数据写入到文件中了。

如何将一段文本内容保存到文件中,并从文件中读取数据?

布局文件

[代码]xml代码:

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context="${relativePackage}.${activityClass}"

    android:orientation="vertical" >

 

    <EditText

        android:id="@+id/edit"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:hint="Type   something here" />

     

    <Button

        android:id="@+id/save_data"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="Save   data"/>

     

    <Button

        android:id="@+id/restore_data"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="Restore   data"/>

</LinearLayout>

MAinActivity.java

[代码]java代码:

?

001

002

003

004

005

006

007

008

009

010

011

012

013

014

015

016

017

018

019

020

021

022

023

024

025

026

027

028

029

030

031

032

033

034

035

036

037

038

039

040

041

042

043

044

045

046

047

048

049

050

051

052

053

054

055

056

057

058

059

060

061

062

063

064

065

066

067

068

069

070

071

072

073

074

075

076

077

078

079

080

081

082

083

084

085

086

087

088

089

090

091

092

093

094

095

096

097

098

099

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

 

import android.app.Activity;

import android.content.Context;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

 

public class MainActivity   extends Activity   {

 

    private EditText edit;

    private Button saveData, restoreData;

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

         

        edit   = (EditText) findViewById(R.id.edit);

        saveData   = (Button) findViewById(R.id.save_data);

        restoreData   = (Button) findViewById(R.id.restore_data);

        String   inputText = load();

        if (!TextUtils.isEmpty(inputText)) {

            edit.setText(inputText);

            edit.setSelection(inputText.length());

            Toast.makeText(this,   "Restoring Succeeded", Toast.LENGTH_SHORT).show();

        }

        saveData.setOnClickListener(new OnClickListener() {

             

            @Override

            public void onClick(View v) {

                //   TODO Auto-generated method stub

                SharedPreferences.Editor   editor = getSharedPreferences("data", MODE_PRIVATE).edit();

                editor.putString("name",   "Tom");

                editor.putInt("age",   23);

                editor.putBoolean("married",   false);

                editor.commit();

            }

        });

        restoreData.setOnClickListener(new OnClickListener() {

             

            @Override

            public void onClick(View v) {

                //   TODO Auto-generated method stub

                SharedPreferences   pref = getSharedPreferences("data", MODE_PRIVATE);

                String   name = pref.getString("name", "");

                int age = pref.getInt("age", 0);

                boolean married = pref.getBoolean("married",   false);

                Toast.makeText(MainActivity.this,   "name=" + name + ",age=" + age + ",married=" + married, Toast.LENGTH_SHORT).show();

            }

        });

    }

 

    @Override

    protected void onDestroy() {

        //   TODO Auto-generated method stub

        super.onDestroy();

        String   inputText = edit.getText().toString();

        save(inputText);

    }

 

    public void save(String inputText) {

        FileOutputStream   fileOutputStream = null;

        BufferedWriter   bufferedWriter = null;

        try {

            fileOutputStream   = openFileOutput("data", Context.MODE_PRIVATE);

            bufferedWriter   = new BufferedWriter(new OutputStreamWriter(fileOutputStream));

            bufferedWriter.write(inputText);

        }   catch (FileNotFoundException   e) {

            //   TODO Auto-generated catch block

            e.printStackTrace();

        }   catch (IOException   e) {

            //   TODO Auto-generated catch block

            e.printStackTrace();

        }   finally {

            try {

                if (bufferedWriter != null) {

                    bufferedWriter.close();

                }

            }   catch (IOException   e) {

                //   TODO Auto-generated catch block

                e.printStackTrace();

            }

        }

    }

 

    public String load() {

        FileInputStream   in = null;

        BufferedReader   reader = null;

        StringBuilder   content = new StringBuilder();

        try {

            in   = openFileInput("data");

            reader   = new BufferedReader(new InputStreamReader(in));

            String   line = "";

            while ((line = reader.readLine()) != null) {

                content.append(line);

            }

        }   catch (FileNotFoundException   e) {

            //   TODO Auto-generated catch block

            e.printStackTrace();

        }   catch (IOException   e) {

            //   TODO Auto-generated catch block

            e.printStackTrace();

        }   finally {

            if (reader != null) {

                try {

                    reader.close();

                }   catch (IOException   e) {

                    //   TODO Auto-generated catch block

                    e.printStackTrace();

                }

            }

        }

        return content.toString();

    }

}

原文链接:http://www.apkbus.com/blog-844891-61525.html

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消