Android数据存储(一)——文件存储

Android主要提供了三种数据存储的方式:文件存储,SharePreferences存储,数据库存储。

文件存储是最基本的数据存储方式,适合存储一些简单的文本或二进制数据

一、将数据存储到文件中

Context类提供了一个方法openFileOutput()

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

1、示例代码

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();
		}
	}
}

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

2、实战

新建一个day11_FilePersistenceTest空项目

a. 主布局

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

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="输入点什么..."
        android:id="@+id/edit"/>

</LinearLayout>

就是一个输入框,输点啥子一旦back掉就没了

b. 主活动

public class MainActivity extends AppCompatActivity {
    private EditText edit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        String inputText = edit.getText().toString();
        save(inputText);
    }

    private void save(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();
            }
        }
    }
}

c. 运行

跑起来输入点东西,关闭掉后重新打开,输入的文本仍然不见了,那么保存的文本在哪呢?
在这里插入图片描述

d. 捕获文件

右下角有个Device File Explorer,在这里可以找到对应的文件
在这里插入图片描述
/data/data/com.example.day11_filepersistence/files/路径下就能找到对应的文件,右键单击导出到电脑里
在这里插入图片描述
打开后就能看到保存的内容
在这里插入图片描述

二、从文件中读取数据

Context类提供了一个方法openFileInput()

  • 只有一个参数,文件名,文件名不包含路径,因为所有文件默认会从/data/data/<package name>/files/目录下读取
  • 也是返回一个FileInputStream对象,通过Java流读取数据

1、示例代码

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();
}

2、实战

直接修改主活动:

  • setSelection()方法使得输入光标移动到末尾位置以便继续输入
  • TextUtils.isEmpty()方法对null字符串和空字符串都会返回true,从而不需要单独判断
public class MainActivity extends AppCompatActivity {
    private EditText edit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edit = findViewById(R.id.edit);
        String inputText = load();
        if (!TextUtils.isEmpty(inputText)){
            edit.setText(inputText);
            edit.setSelection(inputText.length());
            Toast.makeText(this, "读取文件成功!", Toast.LENGTH_LONG).show();
        }
    }

    private String load() {
        FileInputStream fileInputStream = null;
        BufferedReader bufferedReader = null;
        StringBuilder content = new StringBuilder();
        try {
            fileInputStream = openFileInput("data");
            bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
            String line = "";
            while ((line = bufferedReader.readLine()) != null){
                content.append(line);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (bufferedReader != null){
                try {
                    bufferedReader.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        return content.toString();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        String inputText = edit.getText().toString();
        save(inputText);
    }

    private void save(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();
            }
        }

现在重新运行:
在这里插入图片描述
完美!

发布了156 篇原创文章 · 获赞 13 · 访问量 7222

猜你喜欢

转载自blog.csdn.net/qq_41205771/article/details/104177403