安卓开发笔记——-文件存储与本地数据库SQLite(一)

目录

一、文章整体知识结构图

安卓开发笔记-------文件存储与本地数据库SQLite(一)

; 二、文件存储

Android是基于java语言的,在java中提供了一套完整的输入输出流操作体系,与文件有关的有FileInputStream,FileOutputStream等,通过这些类可以很方便的访问磁盘的内容。同样Android也支持这种方式来访问手机上的文件。
Android手机中有两个存储位置:内置存储空间和外部SD卡,针对不同位置文件的存储有所不同。那么接下来我们就看看,Android中如何通过文件来存储数据。

1.手机内置存储空间文件的存取

  • 将数据存储到文件中
    Context类中提供了一个openFileOutput(String name,int mode)方法,可以用于将数据存储到指定的文件中。这个方法接受两个参数。
    第一个参数是文件是文件名,在文件创建的时候使用的就是这个名称 ,这里的文件名不可以指定路径,因为所有的文件都默认存储到/data/data/packagename/files/目录下的。
    第二个参数是文件的操作模式,主要有两种模式可选,MODE_PRIVATE和MODE_APPEND。其中MODE_PRIVATE是默认的操作的模式,代表该文件是私有数据,只能应用本身访问,在该模式下,写入的内容会覆盖源文件的内容。MODE_APPEND则表示如果该文件已经存在,就往文件里面追加内容,不存在就创建新文件。其实文件的操作模式本来应该有四种,但另外两种模式过于危险,容易产生安全漏洞,已经在Android4.2版本中被废弃。
    *openFileOutput(String name,int mode)方法返回的是一个FileOutputStream对象,得到这个对象之后就可以使用java流的方式将数据写入到文件中了。下面看一个简单例子,展示了如何将一段文本内容保存到文件中。
public void save() {
    String data = "Data to save";
    FileOutputStream out = null;
    BufferedWriter writer = null;
    try {
        out = openFileOutput("data", Context.MODE_PRIVATE);
        writer = new BufferedWriter(new OutputStreamWriter(out));
        writer.write(data);
    }catch (IOException e) {
        e.printStackTrace();
    }finally {
        try {
            if (writer != null) {
                writer.close();
            }
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2.从文件中读取数据

类似于将数据存储到文件中,Context类中还提供了一个openFileInput()方法,用于从文件中读取数据。这个方法要比openFileOutput()简单一些,它只接受一个参数,即要读取的文件名,然后系统会自动到/data/data/package name/files/目录去加载这个文件,并返回一个FileInputStream对象,得到这个对象之后再通过Java流的方式就可以将数据读取出来。下面一起来看一个小例子。

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 (IOException e) {
        e.printStackTrace();
    }finally {
        if (reader != null) {
            try {
                reader.close();
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return content.toString();
}

下面来做一个完整的例子。

安卓开发笔记-------文件存储与本地数据库SQLite(一)
MainActivity中的代码
package com.example.file;

import androidx.appcompat.app.AppCompatActivity;

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

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;

public class MainActivity extends AppCompatActivity {
    private EditText readText, writeText;
    private String fileName = "context.txt";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        readText = findViewById(R.id.readText);
        writeText = findViewById(R.id.writeText);

    }
    public void write(View view){
        try {
            FileOutputStream fos = openFileOutput(fileName, Context.MODE_APPEND);
            fos.write(writeText.getText().toString().getBytes());
            writeText.setText("");
            fos.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public void read(View view){
        try {
            FileInputStream fis = openFileInput(fileName);
            StringBuffer sBuffer=new StringBuffer("");
            byte[] buffer=new byte[256];
            int hasRead=0;
            while ((hasRead=fis.read(buffer))!=-1){
                sBuffer.append(new String(buffer,0,hasRead));
            }
            readText.setText(sBuffer.toString());
            fis.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

activity_main中的代码
<?xml version="1.0" encoding="utf-8"?>
<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" android:orientation="vertical" android:padding="10dp">
    <edittext android:id="@+id/writeText" android:layout_width="match_parent" android:layout_height="wrap_content" android:minlines="2" android:hint="&#x8F93;&#x5165;&#x4F60;&#x60F3;&#x5199;&#x7684;&#x6587;&#x672C;">
    <button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="&#x5199;&#x5165;" android:onclick="write">

    <edittext android:id="@+id/readText" android:layout_width="match_parent" android:layout_height="wrap_content" android:enabled="false" android:hint="&#x663E;&#x793A;&#x8BFB;&#x53D6;&#x7684;&#x5185;&#x5BB9;">

    <button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="&#x8BFB;&#x53D6;" android:onclick="read">

</button></edittext></button></edittext></linearlayout>

Original: https://blog.csdn.net/m0_55584761/article/details/127943079
Author: 哥哥的梦
Title: 安卓开发笔记——-文件存储与本地数据库SQLite(一)

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/815739/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球