如何在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 中讀取/寫入檔案中的字串。