如何在Android中讀取SD卡上的文字檔案?


簡介

在Android應用程式中,我們經常需要下載特定檔案並將其儲存到裝置的外部儲存中。有時我們需要從裝置的外部儲存訪問這些檔案,並在我們的Android應用程式中顯示這些檔案的內容。本文將介紹如何在Android中讀取SD卡上的文字檔案。

實現

我們將建立一個簡單的應用程式,其中我們將顯示兩個TextView。在第一個TextView中,我們將顯示應用程式的標題,在第二個TextView中,我們將顯示要從儲存在外部儲存中的檔案中讀取的訊息。

步驟1:在Android Studio中建立一個新專案

導航到Android Studio,如下面的螢幕截圖所示。在下面的螢幕截圖中,點選“新建專案”以建立一個新的Android Studio專案。

點選“新建專案”後,您將看到下面的螢幕。

在此螢幕中,我們只需選擇“空活動”並點選“下一步”。點選“下一步”後,您將看到下面的螢幕。

在此螢幕中,我們只需指定專案名稱。然後包名將自動生成。

注意 - 確保選擇Java作為語言。

指定所有詳細資訊後,點選“完成”以建立一個新的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="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical"
   tools:context=".MainActivity">

   <!-- on below line creating a text view for displaying a heading-->
   <TextView
      android:id="@+id/idTVHeading"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_above="@id/idTVMsg"
      android:layout_margin="10dp"
      android:padding="4dp"
      android:text="How to read a text file from the SD card in Android?"
      android:textAlignment="center"
      android:textColor="@color/black"
      android:textSize="20sp"
      android:textStyle="bold" />

   <!-- on below line creating a text view for displaying a message from our file-->
   <TextView
      android:id="@+id/idTVMsg"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:text="Message"
      android:textAlignment="center"
      android:textColor="@color/black"
      android:textSize="18sp" />
</RelativeLayout>

解釋 - 在上面的程式碼中,根元素是Android中的RelativeLayout。此佈局是一個ViewGroup,用於相對於彼此對齊其中的所有元素。我們可以藉助ID或位置在RelativeLayout中相對對齊所有元素。

在此RelativeLayout中,我們建立了兩個TextView。在第一個TextView中,我們顯示應用程式的標題,而在第二個TextView中,我們將顯示來自外部儲存中檔案的內容。

最後,我們為RelativeLayout添加了一個結束標籤,因為TextView和Button都包含在我們的RelativeLayout中。

步驟3:在AndroidManifest.xml檔案中新增檔案讀取許可權以從外部儲存讀取檔案。

導航到app>manifests>AndroidManifest.xml檔案,並在manifest標籤中新增網際網路許可權。

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

解釋 - 因為我們從外部儲存開啟檔案,所以必須在AndroidManifest.xml檔案中提供讀取外部儲存的許可權。

步驟4:使用MainActivity.java。

導航到MainActivity.java。如果此檔案不可見,要開啟此檔案,請在左側窗格中導航到app>java>您的應用程式的包名>MainActivity.kt以開啟此檔案。開啟此檔案後,將以下程式碼新增到其中。程式碼中添加了註釋以詳細瞭解。

package com.example.androidjavaapp;

import androidx.appcompat.app.AppCompatActivity;
import android.content.ContextWrapper;
import android.os.Bundle;
import android.os.Environment;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class MainActivity extends AppCompatActivity {
   // on below line creating a variables
   private TextView msgTV;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      // on below line initializing web view with id.
      msgTV = findViewById(R.id.idTVMsg);

      // on below line creating a 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);
      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 the below line setting data to our text view. msgTV.setText(text); } }

解釋 - 在上面MainActivity.java檔案的程式碼中。首先,我們為TextView建立一個變數。

現在我們將看到onCreate方法。這是每個Android應用程式的預設方法。當建立應用程式檢視時,將呼叫此方法。在此方法內部,我們設定內容檢視,即名為activity_main.xml的佈局檔案,以從該檔案中設定UI。

指定檢視後,我們使用我們在activity_main.xml檔案中指定的唯一ID初始化名為msgTV的TextView變數。

初始化TextView後,我們為要從中讀取檔案的檔案建立一個變數,並將檔名指定為file.txt。請確保根據儲存在裝置中的檔案更改檔名。然後,我們建立一個StringBuilder,用於從該檔案中讀取資料。

最後,我們透過呼叫setText方法將從檔案中讀取的內容設定到msgTV中。

新增上述程式碼後,我們只需點選頂欄中的綠色圖示即可在移動裝置上執行我們的應用程式。

注意 - 確保已連線到您的真實裝置或模擬器。

輸出

結論

在上面的教程中,我們學習瞭如何讀取儲存在外部儲存中的文字檔案中的資料。

更新於: 2023年3月30日

1K+ 次檢視

開啟您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.