Android 数据存储-内外部存储测试

案例分析:FilePersistenceTest

在EditText中输入文本内容,退出应用程序或者 单击“保存”按钮时

保存EditText中的数据到名 为“data”的文件中。

打开Device File Explorer,该文件应该存于 /data/data/cn.edu.hunnu.filepersistencetest/files/ 目录

 

 MainActivity.java

package cn.edu.hunnu.filepersisttest;

import android.content.Context;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class MainActivity extends AppCompatActivity {
    private EditText edit;
    private Button bt_save_in;
    private Button bt_read_in;
    private Button bt_save_out;
    private Button bt_read_out;
    private Button bt_clr_edit;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

        bt_clr_edit = (Button)findViewById(R.id.bt_clr_edit);
        bt_clr_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                edit.setText("");
            }
        });

        bt_save_in = (Button)findViewById(R.id.bt_save_in);
        bt_save_in.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String inputText = edit.getText().toString();
                saveToInternalStorage(inputText);
                Toast.makeText(MainActivity.this,"Save to internal storage succeeded",
                        Toast.LENGTH_SHORT).show();
            }
        });
        bt_read_in =(Button)findViewById(R.id.bt_read_in);
        bt_read_in.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String inputText = loadFromInternalStorage();
                if (!TextUtils.isEmpty(inputText)) {
                    edit.setText(inputText);
                    edit.setSelection(inputText.length());
                    Toast.makeText(MainActivity.this, "Restoring from internal storage succeeded", Toast.LENGTH_SHORT).show();
                }
            }
        });

        bt_save_out = (Button)findViewById(R.id.bt_save_out);
        bt_save_out.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String inputText = edit.getText().toString();
                saveToExternalStorage(inputText);
                Toast.makeText(MainActivity.this,"Save to external storage succeeded",
                        Toast.LENGTH_SHORT).show();
            }
        });

        bt_read_out = (Button)findViewById(R.id.bt_read_out);
        bt_read_out.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String inputText = loadFromExternalStorage();
                if (!TextUtils.isEmpty(inputText)) {
                    edit.setText(inputText);
                    edit.setSelection(inputText.length());
                    Toast.makeText(MainActivity.this, "Restoring from external storage succeeded", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public void saveToInternalStorage(String inputText) {
        FileOutputStream out = null;
        BufferedWriter writer = null;
        try {
            out = openFileOutput("data", Context.MODE_PRIVATE);
            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();
            }
        }
    }
    public String loadFromInternalStorage() {
        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 (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return content.toString();
    }

    public void saveToExternalStorage(String inputText) {
        String environment = Environment.getExternalStorageState();
        if(Environment.MEDIA_MOUNTED.equals(environment)) {
            //外部设备可以进行读写操作
            //保存在外部存储根目录,卸载应用时不能删除该文件
            //File sd_path = Environment.getExternalStorageDirectory();
//            Log.e("MainActivity",sd_path.toString());
//            File file = new File(sd_path,"test.txt");
            //保存在外部私有目录,卸载时会同时删除该文件
            String sd_path = this.getExternalFilesDir("").getAbsolutePath();
            Log.e("MainActivity+",sd_path);
            File file = new File(sd_path);
            if(!file.exists()){//判断文件目录是否存在
                file.mkdirs();
            }
            file = new File(sd_path,"text.txt");
            FileOutputStream fos;
            try{//写入数据
                fos = new FileOutputStream(file);
                OutputStreamWriter  osw = new OutputStreamWriter(fos);
                osw.write(inputText);
                osw.flush();
                osw.close();
                fos.close();
            }catch(Exception exception){
                exception.printStackTrace();
            }
        }
    }

    public String loadFromExternalStorage() {
        String content = null;
        String environment = Environment.getExternalStorageState();
        if(Environment.MEDIA_MOUNTED.equals(environment)) {
//            File sd_path = Environment.getExternalStorageDirectory();
//            Log.e("MainActivity",sd_path.toString());
//            File file = new File(sd_path,"test.txt");
            String sd_path = this.getExternalFilesDir("").getAbsolutePath();
            File file = new File(sd_path,"text.txt");
            Log.e("MainActivity+",file.getPath());

            FileInputStream fis;
            try{//读取文件
                fis = new FileInputStream(file);
                InputStreamReader  isr = new InputStreamReader(fis,"UTF-8");
                char[] input = new char[fis.available()];
                isr.read(input);
                content = new String(input);
                isr.close();
                fis.close();
            }catch(Exception exception){
                exception.printStackTrace();
            }
        }
        return content;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        String inputText = edit.getText().toString();
        saveToInternalStorage(inputText);
        Toast.makeText(MainActivity.this,"Save to internal storage succeeded",
                Toast.LENGTH_SHORT).show();
    }
}

 

 activity_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:padding="5dp"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/edit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Type something here" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/bt_save_in"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="保存(内部存储)" />

        <Button
            android:id="@+id/bt_read_in"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="读取(内部存储)" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/bt_save_out"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="保存(外部存储)" />

        <Button
            android:id="@+id/bt_read_out"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="读取(外部存储)" />

    </LinearLayout>

    <Button
        android:id="@+id/bt_clr_edit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="清空输入框" />

</LinearLayout>

 AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.filepersisttest">
    <uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name = "android.permission. READ_EXTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 

 

 

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值