如何在Android中读取/写入文件中的字符串?


简介

在构建 Android 应用程序时,我们经常需要将数据以文件的形式存储在应用程序中。我们将读取和写入文件中的字符串数据。本文将介绍如何在 Android 中读取/写入文件中的字符串。

实现

我们将创建一个简单的应用程序,首先将用户通过 EditText 输入的数据写入文件,然后通过点击按钮读取文件中存储的数据,并在 TextView 中显示。

步骤 1:在 Android Studio 中创建一个新项目

导航到 Android Studio,如下面的屏幕所示。在下面的屏幕中,点击“新建项目”以创建一个新的 Android Studio 项目。

点击“新建项目”后,您将看到下面的屏幕。

在这个屏幕中,我们只需选择“Empty Activity”并点击“Next”。点击“Next”后,您将看到下面的屏幕。

在这个屏幕中,我们只需指定项目名称。然后包名将自动生成。

注意:确保选择 Java 作为语言。

指定所有详细信息后,点击“Finish”以创建一个新的 Android Studio 项目。

项目创建完成后,我们将看到两个打开的文件:activity_main.xml 和 MainActivity.java 文件。

步骤 2:使用 activity_main.xml

导航到 activity_main.xml。如果此文件不可见,则打开此文件。在左侧面板中导航到 app>res>layout>activity_main.xml 以打开此文件。打开此文件后,向其中添加以下代码。代码中添加了注释以便详细了解。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
   tools:context=".MainActivity">
   <!-- creating a text view on below line-->
   <TextView
       android:id="@+id/idTVMessage"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_marginStart="20dp"
       android:layout_marginTop="20dp"
       android:layout_marginEnd="20dp"
       android:layout_marginBottom="20dp"
       android:padding="4dp"
       android:text="Read/Write String from File in Android"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="20sp"
       android:textStyle="bold" />
   <!-- creating an edit text on below line -->
   <EditText
       android:id="@+id/idEdtMsg"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idTVMessage"
       android:layout_margin="10dp"
       android:hint="Enter message to be saved" />
   <!-- creating a button to write in a file -->
   <Button
       android:id="@+id/idBtnWrite"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idEdtMsg"
       android:layout_marginStart="10dp"
       android:layout_marginTop="10dp"
       android:layout_marginEnd="10dp"
       android:layout_marginBottom="10dp"
       android:text="Write File"
       android:textAllCaps="false" />
   <!-- creating a text view to display the data from a file-->
   <TextView
       android:id="@+id/idTVReadFile"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idBtnWrite"
       android:layout_marginStart="10dp"
       android:layout_marginTop="50dp"
       android:layout_marginEnd="10dp"
       android:layout_marginBottom="10dp"
       android:padding="4dp"
       android:text="File content will appear here"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="18sp" />
   <!-- creating a button for reading data from a file -->
   <Button
       android:id="@+id/idBtnRead"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idTVReadFile"
       android:layout_marginStart="10dp"
       android:layout_marginTop="10dp"
       android:layout_marginEnd="10dp"
       android:layout_marginBottom="10dp"
       android:text="Read File"
       android:textAllCaps="false" />
</RelativeLayout>

说明:在上面的代码中,我们创建了一个根布局作为相对布局。在这个布局中,我们创建了一个 TextView 用于显示应用程序的标题。之后,我们创建了一个按钮,我们将使用它来请求读取移动设备上的短信的权限。

步骤 3:在 AndroidManifest.xml 文件中添加权限

导航到 app>AndroidManifest.xml 文件,并在 manifest 标签中添加以下权限以读取短信。

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

步骤 4:使用 MainActivity.java 文件

导航到 MainActivity.java。如果此文件不可见,则打开此文件。在左侧面板中导航到 app>res>layout>MainActivity.java 以打开此文件。打开此文件后,向其中添加以下代码。代码中添加了注释以便详细了解。

package com.example.java_test_application;
import android.Manifest;
import android.content.ContextWrapper;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStreamWriter;
public class MainActivity extends AppCompatActivity {
   // creating variables on below line for button.
   private Button readBtn, writeBtn;
   private EditText msgEdt;
   private TextView msgTV;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      // initializing variables on below line.
      readBtn = findViewById(R.id.idBtnRead);
      writeBtn = findViewById(R.id.idBtnWrite);
      msgEdt = findViewById(R.id.idEdtMsg);
      msgTV = findViewById(R.id.idTVReadFile);
      // on below line adding click listener for short message button.
      readBtn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            // on below line we are checking the self permissions for reading sms.
            ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
            // on below line creating a directory for file and specifying the file name.
            File directory = contextWrapper.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
            Log.e("TAG", "download is : " + directory.getAbsolutePath() + "
" + directory); File txtFile = new File(directory, "file" + ".txt"); // on below line creating a string builder. StringBuilder text = new StringBuilder(); try { // on below line creating and initializing buffer reader. BufferedReader br = new BufferedReader(new FileReader(txtFile)); // on below line creating a string variable/ String line; // on below line setting the data to text while ((line = br.readLine()) != null) { text.append(line); text.append('
'); } br.close(); // on below line handling the exception } catch (Exception e) { Toast.makeText(getApplicationContext(), "Fail to read the file..", Toast.LENGTH_SHORT).show(); } // on below line setting string from file to our text view. msgTV.setText(text); Toast.makeText(contextWrapper, "File read successful..", Toast.LENGTH_SHORT).show(); } }); writeBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line getting data from our edit text. String text = msgEdt.getText().toString(); // on below line validating if edit text is empty or not. if (text.isEmpty()) { Toast.makeText(MainActivity.this, "Please enter the data to be saved..", Toast.LENGTH_SHORT).show(); return; } // on below line creating and initializing variable for context wrapper. ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext()); // on below line creating a directory for file and specifying the file name. File directory = contextWrapper.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS); // on below line creating a text file. File txtFile = new File(directory, "file" + ".txt"); // on below line writing the text to our file. FileOutputStream fos = null; try { fos = new FileOutputStream(txtFile); OutputStreamWriter osw = new OutputStreamWriter(fos); osw.write(text); osw.flush(); osw.close(); fos.close(); Toast.makeText(contextWrapper, "File write successful..", Toast.LENGTH_SHORT).show(); msgEdt.setText(""); } catch (Exception e) { // on below line handling the exception. e.printStackTrace(); } } }); } }

说明 - 在上面的代码中,我们首先为 TextView、按钮和 EditText 创建变量。现在我们将看到 onCreate 方法。这是每个 Android 应用程序的默认方法。当应用程序视图创建时,将调用此方法。在此方法中,我们设置内容视图,即名为 activity_main.xml 的布局文件,以设置来自该文件 UI。在 onCreate 方法中,我们使用我们在 activity_main.xml 文件中给出的 ID 初始化按钮、EditText 和 TextView 的变量。之后,我们为读取按钮添加一个点击侦听器。在 onclick 侦听器中,我们从文件中读取数据并将其设置在 TextView 中。

之后,我们为写入按钮添加一个点击侦听器。在此方法中,我们将用户在 EditText 字段中输入的数据写入我们的文件。

添加上述代码后,我们只需点击顶部的绿色图标即可在移动设备上运行我们的应用程序。

注意:确保您已连接到您的真实设备或模拟器。

输出

结论

在本文中,我们介绍了如何在 Android 中读取/写入文件中的字符串。

更新于:2023年5月9日

2K+ 次浏览

启动您的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.