Android 入门(7)——文件持久化存储

我们在编程的时候,难免会遇到数据保存的情况。例如,当我们与别人进行聊天的时候,发送的消息或者接收到的消息,肯定不能发完之后切换一个页面,再切换回来之后就消失了。想必那样的程序一定是让人抓狂的。

这篇文章我们将介绍一下Android的两种简单的文件存储方式

  1. 文件存储
  2. SharedPreferences 存储

将数据存储在文件中

Android提供了一个函数openFileOutPut用于进行文件创建与打开,这个函数有两个参数,一个是文件的名字,另一个是打开的方式。

Context.MODE_PRIVATE(默认模式,打开文件并覆盖写入)
Context.MODE_APPEND(后加模式,打开文件并追加到后面)

openFileOutPut返回一个FileOutputStream对象
然后利用BufferedWriterwrite方法将数据写入文件中

示例

创建一个新的项目FileIOTest,打开active_main.xml编写以下界面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/put_data"
        android:hint="output data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <EditText
        android:id="@+id/get_data"
        android:hint="input data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/put_button"
        android:text="put"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/get_button"
        android:text="get"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

效果
效果图

接下来打开MainActivity.java,进行我们的主代码编写

public class MainActivity extends AppCompatActivity {
    private Button getButton;
    private Button putButton;
    private EditText putEdit;
    private EditText getEdit;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getButton = (Button)findViewById(R.id.get_button);
        putButton = (Button)findViewById(R.id.put_button);
        putEdit = (EditText)findViewById(R.id.put_data);
        getEdit = (EditText)findViewById(R.id.get_data);
        putButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String getData = putEdit.getText().toString();
                saveData(getData);
            }
        });

    }
    void saveData(String inputText){
        FileOutputStream out = null;
        BufferedWriter writer = null;
        try{
            out = openFileOutput("data",Context.MODE_APPEND);
            writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write(inputText);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try{
                if(writer !=null){
                    writer.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
    void getData(){
        String get_Data = "";
    }
}
  1. 代码有点长,我们分开来看。首先看oncreate函数里面。我们主要是获取了每一个控件的引用,并且给putButton设置点击事件。
  2. 然后获取FileOutPutStream对象,利用这个对象初始化写入对象BufferedWriter。
  3. 最后利用writer.write(data)写入。

从文件中获取数据

由于只是写入数据不够全面,这里将获取数据一同作为一个整体讲解。
Android给我们同样提供了读取数据函数openFileInput,这个函数指需要传进去一个参数,就是文件名。
使用也很简单,通过openFileInput获取FileInputString对象,利用FileInputStream对象初始化BufferedReader,然后利用BufferedReaderreadLine读取数据。

    String getData(){
        String inputString= "";
        FileInputStream in = null;
        BufferedReader reader = null;
        StringBuilder builder = new StringBuilder();
        try{
            in = openFileInput("data");
            reader = new BufferedReader(new InputStreamReader(in));
            while((inputString = reader.readLine())!=null){
                builder.append(inputString);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(reader!=null){
                try {
                    reader.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        return builder.toString();
    }

上述代码实现读取data文件并且将所有数据都读出来
在主函数进行点击事件写入

       getButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String getString = getData();
                getEdit.setText(getString);
            }
        });

效果

输入三次数据,第一次输入firstdata,第二次seconddata,第三次thirddata,最后获取所有输入的数据,即为测试成功


测试

使用SharedPerferences

SharedPerferences存储文件格式为xml
存储格式为键、值对。
Context中getSharedPerferences,第一个用于指定存储文件名,第二个用于打开文件格式。
目前打开格式只有:MODE_PRIVATE

使用步骤:

  1. 调用SharedPreferences对象的edit()函数返回一个SharedPreferenced.Editor对象
  2. 利用各种put函数向SharedPreferences.Editor中传入数据
    如传入String使用putString()。
  3. 使用apply()提交数据。

制作简单界面

界面
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:id="@+id/your_id"
            android:hint="Id"
            android:layout_width="0sp"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
        <EditText
            android:id="@+id/your_password"
            android:hint="Password"
            android:layout_width="0sp"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>

    </LinearLayout>
    <Button
        android:id="@+id/button"
        android:text="set_Message"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

主函数

public class MainActivity extends AppCompatActivity {

    Button button;
    EditText idEdit;
    EditText passwordEdit;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button =(Button)findViewById(R.id.button);
        idEdit = (EditText)findViewById(R.id.your_id);
        passwordEdit = (EditText)findViewById(R.id.your_password);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String Id = idEdit.getText().toString();
                String Password = passwordEdit.getText().toString();
                SharedPreferences.Editor editor = getSharedPreferences("DataList",MODE_PRIVATE).edit();
                editor.putString("Id",Id);
                editor.putString("password",Password);
                editor.apply();
            }
        });

    }
}

输入数据

使用

查看DataList.xml

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="password">4787897894984</string>
    <string name="Id">154967797</string>
</map>

获取存入的数据也很简单,使用getSharedPreferences获取SharedPreferences对象,然后使用getString(键)来获取相应的值

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,110评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,443评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,474评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,881评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,902评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,698评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,418评论 3 419
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,332评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,796评论 1 316
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,968评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,110评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,792评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,455评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,003评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,130评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,348评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,047评论 2 355

推荐阅读更多精彩内容