📜  Android中的内部存储示例

📅  最后修改于: 2021-05-08 20:42:26             🧑  作者: Mango

本文的目的是向用户展示如何使用内部存储。在本文中,将创建一个应用程序,该应用程序可以将数据写入文件,并将其存储在内部存储器中,并从文件中读取数据,并使用TextView将其显示在主要活动上。在内部存储器上保存和加载数据是某个应用程序专用的,其他应用程序无法访问该应用程序。卸载应用程序后,该应用程序存储在内部的数据将被删除。要在android内部存储中进行读写,我们有两种方法

  • OpenFileOutput():用于创建和保存文件。此方法返回FileOutputStream实例。
  • OpenFileInput():用于从文件读取数据,这将返回FileInputStream实例。

例子

下面给出了一个示例GIF,以了解我们将在本文中做些什么。注意,我们将使用Java语言实现该项目。

Android示例GIF中的内部存储

分步实施

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。

步骤2:使用activity_main.xml文件

activity_main.xml文件具有以下小部件

  1. 一个EditText接受用户输入
  2. 两个按钮,一个用于读取数据,另一个用于写入
  3. 一个TextView显示文件内容

以下是activity_main.xml文件的代码。

XML


  
    
  
    


Java
private String filename = "demoFile.txt";
read = findViewById(R.id.read_button);
write = findViewById(R.id.write_button);
userInput = findViewById(R.id.userInput);
fileContent = findViewById(R.id.content);


Java
private void readData()
{
  
    try 
    {
      FileInputStream fin = openFileInput(filename);
      int a;
      StringBuilder temp = new StringBuilder();
      while ((a = fin.read()) != -1) 
      {
        temp.append((char)a);
      }
        
      // setting text from the file.
      fileContent.setText(temp.toString());
      fin.close();
     }
    catch (IOException e) 
    {
      e.printStackTrace();
    }
  printMessage("reading to file " + filename + " completed..");
}


Java
private void writeData()
{
    try
    {
      FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
      String data = userInput.getText().toString();
      fos.write(data.getBytes());
      fos.flush();
      fos.close();
    }
    catch (IOException e) 
    {
      e.printStackTrace();
    }
    userInput.setText("");
    printMessage("writing to file " + filename + "completed...");
}


Java
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
  
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
  
    // declare the variables
    Button read, write;
    EditText userInput;
    TextView fileContent;
  
    private String filename = "demoFile.txt";
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        read = findViewById(R.id.read_button);
        write = findViewById(R.id.write_button);
        userInput = findViewById(R.id.userInput);
        fileContent = findViewById(R.id.content);
  
        read.setOnClickListener(this);
        write.setOnClickListener(this);
    }
  
    public void printMessage(String m) {
        Toast.makeText(this, m, Toast.LENGTH_LONG).show();
    }
  
    @Override
    public void onClick(View view) {
        Button b = (Button) view;
  
        // get the button text : in out case either read or
        // write depending on the button pressed.
        String b_text = b.getText().toString();
  
        switch (b_text.toLowerCase()) {
            case "write": {
                writeData();
                break;
            }
            case "read": {
                readData();
                break;
            }
        }
    }
  
    private void writeData() {
  
        try {
            FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
            String data = userInput.getText().toString();
            fos.write(data.getBytes());
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        userInput.setText("");
        printMessage("writing to file " + filename + "completed...");
    }
  
    private void readData() {
        try {
            FileInputStream fin = openFileInput(filename);
            int a;
            StringBuilder temp = new StringBuilder();
            while ((a = fin.read()) != -1) {
                temp.append((char) a);
            }
  
            // setting text from the file.
            fileContent.setText(temp.toString());
            fin.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        printMessage("reading to file " + filename + " completed..");
    }
}


输出界面:

输出界面

步骤3:使用MainActivity。 Java文件

MainActivity内部我们将在Java文件中执行以下操作:

初始化变量:

Java

private String filename = "demoFile.txt";
read = findViewById(R.id.read_button);
write = findViewById(R.id.write_button);
userInput = findViewById(R.id.userInput);
fileContent = findViewById(R.id.content);

将要创建的文件是DemoFile.txt。可以在“设备文件资源管理器”>“数据”>“数据”>“ application_package”>“文件”中找到

读写方法:

以下方法用于从内部数据读取数据。

Java

private void readData()
{
  
    try 
    {
      FileInputStream fin = openFileInput(filename);
      int a;
      StringBuilder temp = new StringBuilder();
      while ((a = fin.read()) != -1) 
      {
        temp.append((char)a);
      }
        
      // setting text from the file.
      fileContent.setText(temp.toString());
      fin.close();
     }
    catch (IOException e) 
    {
      e.printStackTrace();
    }
  printMessage("reading to file " + filename + " completed..");
}

用于创建文件并将数据写入内部存储器的方法。

Java

private void writeData()
{
    try
    {
      FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
      String data = userInput.getText().toString();
      fos.write(data.getBytes());
      fos.flush();
      fos.close();
    }
    catch (IOException e) 
    {
      e.printStackTrace();
    }
    userInput.setText("");
    printMessage("writing to file " + filename + "completed...");
}

以下是MainActivity的完整代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。

Java

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
  
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
  
    // declare the variables
    Button read, write;
    EditText userInput;
    TextView fileContent;
  
    private String filename = "demoFile.txt";
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        read = findViewById(R.id.read_button);
        write = findViewById(R.id.write_button);
        userInput = findViewById(R.id.userInput);
        fileContent = findViewById(R.id.content);
  
        read.setOnClickListener(this);
        write.setOnClickListener(this);
    }
  
    public void printMessage(String m) {
        Toast.makeText(this, m, Toast.LENGTH_LONG).show();
    }
  
    @Override
    public void onClick(View view) {
        Button b = (Button) view;
  
        // get the button text : in out case either read or
        // write depending on the button pressed.
        String b_text = b.getText().toString();
  
        switch (b_text.toLowerCase()) {
            case "write": {
                writeData();
                break;
            }
            case "read": {
                readData();
                break;
            }
        }
    }
  
    private void writeData() {
  
        try {
            FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
            String data = userInput.getText().toString();
            fos.write(data.getBytes());
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        userInput.setText("");
        printMessage("writing to file " + filename + "completed...");
    }
  
    private void readData() {
        try {
            FileInputStream fin = openFileInput(filename);
            int a;
            StringBuilder temp = new StringBuilder();
            while ((a = fin.read()) != -1) {
                temp.append((char) a);
            }
  
            // setting text from the file.
            fileContent.setText(temp.toString());
            fin.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        printMessage("reading to file " + filename + " completed..");
    }
}

输出

想要一个节奏更快,更具竞争性的环境来学习Android的基础知识吗?
单击此处,前往由我们的专家精心策划的指南,以使您立即做好行业准备!