Android中實現保存和讀取文本文件到內部存儲器(實現簡易的記事本為例)


場景

在Android應用中需要將某些文本內容保存到存儲器中的txt文件中。

在顯示時還需要將txt文件的內容讀取加載出來。形成一個簡單記事本的效果

 

 

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。

實現

首先新建一個Activity並設計頁面布局如上,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=".StoreTextActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:gravity="center_horizontal"
        android:textSize="18sp"
        android:textColor="@android:color/black"
        android:text="記事本"
        />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#FFC8C8C8"/>
    <EditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="start"
        android:hint="請輸入文本"
        android:inputType="textMultiLine"
        />

    <Button
        android:id="@+id/btn_save"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="saveFile"
        android:text="保存"
        />
</LinearLayout>

 

然后在Activity,在保存按鈕的點擊事件執行的保存到文件的方法中,將editText的文本內容保存到文件

 

   /***
     * 保存到文件
     * @param str
     */
    public void saveFile(String str)
    {
        FileOutputStream fos = null;
        BufferedWriter writer = null;

        try {
            fos = openFileOutput("badao.txt", Context.MODE_PRIVATE);
            writer = new BufferedWriter(new OutputStreamWriter(fos));
            try {
                writer.write(str);
                Toast.makeText(this,"保存成功",Toast.LENGTH_LONG).show();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            if(writer!=null)
            {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

 

保存成功后,文件會在內部存儲下data/data/包名/files下找到

 

 

然后在onCreate方法中,首先執行從txt加載內容的方法

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_store_text);
        editText = findViewById(R.id.edit_text);
        String str = load();
        if(!(TextUtils.isEmpty(str)))
        {
            editText.setText(str);
            Toast.makeText(this,"加載成功",Toast.LENGTH_LONG).show();
        }
    }

 

在加載內容的方法load中

 

   /***
     * 從文件中加載
     * @return
     */
    public String load()
    {
        FileInputStream fis = null;
        BufferedReader reader = null;
        StringBuilder content = new StringBuilder();
        try {
            fis = openFileInput("badao.txt");
            reader = new BufferedReader(new InputStreamReader(fis));
            String str;

            while ((str=reader.readLine())!=null) {
                content.append(str);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(reader!=null)
            {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fis!=null)
            {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return content.toString();
    }

 

activity的完整代碼

package com.badao.androidstudy;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

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;

public class StoreTextActivity extends AppCompatActivity {

    private EditText editText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_store_text);
        editText = findViewById(R.id.edit_text);
        String str = load();
        if(!(TextUtils.isEmpty(str)))
        {
            editText.setText(str);
            Toast.makeText(this,"加載成功",Toast.LENGTH_LONG).show();
        }
    }


    public void saveFile(View view)
    {
        saveFile(editText.getText().toString());
    }


    /***
     * 從文件中加載
     * @return
     */
    public String load()
    {
        FileInputStream fis = null;
        BufferedReader reader = null;
        StringBuilder content = new StringBuilder();
        try {
            fis = openFileInput("badao.txt");
            reader = new BufferedReader(new InputStreamReader(fis));
            String str;

            while ((str=reader.readLine())!=null) {
                content.append(str);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(reader!=null)
            {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fis!=null)
            {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return content.toString();
    }

    /***
     * 保存到文件
     * @param str
     */
    public void saveFile(String str)
    {
        FileOutputStream fos = null;
        BufferedWriter writer = null;

        try {
            fos = openFileOutput("badao.txt", Context.MODE_PRIVATE);
            writer = new BufferedWriter(new OutputStreamWriter(fos));
            try {
                writer.write(str);
                Toast.makeText(this,"保存成功",Toast.LENGTH_LONG).show();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            if(writer!=null)
            {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

運行之后,輸入一些文本內容,點擊保存

 

 

然后退出app重新啟動后

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM