如何在Android中儲存檔案到外部儲存?


簡介

在Android裝置中,最實用的功能是儲存和讀取裝置儲存或外部儲存中的檔案。這允許使用者擴充套件其裝置儲存容量,以便能夠根據需要儲存和檢索檔案,並相應地使用它們。本文將探討如何在Android中將檔案儲存到外部儲存。

實現

我們將建立一個簡單的應用程式,其中我們將建立一個TextView來顯示應用程式的標題。然後,我們將建立一個EditText欄位,從中讀取使用者想要儲存到外部儲存中的資料。接下來,我們將新增一個按鈕,用於將此資料以檔案的形式儲存到裝置的外部儲存或SD卡中。之後,我們將顯示一個TextView和另一個按鈕,用於讀取資料。當用戶點選此“讀取資料”按鈕時,我們將從外部儲存讀取檔案,並將該檔案中的資料設定到我們的TextView中。現在讓我們轉向Android Studio建立一個新專案。

步驟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">
   <!-- on below line creating the heading of our application -->
   <TextView
       android:id="@+id/idTVHeading"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_margin="10dp"
       android:layout_marginTop="90dp"
       android:padding="8dp"
       android:text="Save File in External Storage in Android"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="20sp"
       android:textStyle="bold" />
   <!-- on below line creating an edit text for storing the data in the file -->
   <EditText
       android:id="@+id/idEdtMessage"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idTVHeading"
       android:layout_margin="10dp"
       android:hint="Enter the data to be saved in the file.."
       android:lines="4" />
   <!-- on below line creating a button to save this image view in external storage-->
   <Button
       android:id="@+id/idBtnSave"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idEdtMessage"
       android:layout_margin="10dp"
       android:text="Save File To External Storage"
       android:textAllCaps="false" />
   <!-- on below line creating a text view for displaying the file data -->
   <TextView
       android:id="@+id/idTVFileData"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idBtnSave"
       android:layout_centerHorizontal="true"
       android:layout_margin="10dp"
       android:padding="4dp"
       android:text="File Data will appear here"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="18sp" />
   <!-- on below line creating a button to view the file stored in external storage-->
   <Button
       android:id="@+id/idBtnView"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idTVFileData"
       android:layout_margin="10dp"
       android:text="View File Data"
       android:textAllCaps="false" />
</RelativeLayout>

說明:在上面的程式碼中,我們建立了一個根佈局作為相對佈局。在這個佈局中,我們建立了一個TextView來顯示應用程式的標題。之後,我們建立了一個EditText欄位,用於獲取要儲存到檔案中的使用者輸入。然後,我們建立一個按鈕,用於生成檔案並將文字輸入欄位中的資料儲存到SD卡或外部儲存中。之後,我們建立了一個TextView和一個按鈕。我們將使用一個按鈕從外部儲存讀取檔案,並將該檔案中的資料顯示在我們建立的TextView中。

步驟3:在AndroidManifest.xml檔案中新增許可權

導航到app>AndroidManifest.xml檔案,並在manifest標籤中新增以下許可權以讀取外部儲存。

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

步驟4:使用MainActivity.java檔案

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

package com.example.java_test_application;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.IntentSender;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Telephony;
import android.text.TextUtils;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.credentials.Credential;
import com.google.android.gms.auth.api.credentials.CredentialPickerConfig;
import com.google.android.gms.auth.api.credentials.CredentialRequest;
import com.google.android.gms.auth.api.credentials.CredentialRequestResult;
import com.google.android.gms.auth.api.credentials.Credentials;
import com.google.android.gms.auth.api.credentials.CredentialsClient;
import com.google.android.gms.auth.api.credentials.CredentialsOptions;
import com.google.android.gms.auth.api.credentials.HintRequest;
import com.google.android.gms.auth.api.credentials.IdentityProviders;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
   // creating variable for edit text on below line.
   private EditText msgEdt;
   // creating variables for button on below line.
   private Button saveFileBtn, viewFileBtn;
   // creating variable for text view on below line to display the data from the file.
   private TextView dataTV;
   File externalFile;
   private String filename = "file.txt";
   private String filepath = "files";
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       // initializing variables for text view on below line.
       saveFileBtn = findViewById(R.id.idBtnSave);
       viewFileBtn = findViewById(R.id.idBtnView);
       msgEdt = findViewById(R.id.idEdtMessage);
       dataTV = findViewById(R.id.idTVFileData);
       // on below line we are checking if the external storage is available on the device and the external storage is not read only.
       if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
           // if the external storage is not avialable then we are displaying the toast message on below line.
           Toast.makeText(this, "External storage not available on the device..", Toast.LENGTH_SHORT).show();
       } else {
           // on below line we are initializing external file variable and specifying the file path along with file name.
           externalFile = new File(getExternalFilesDir(filepath), filename);
       }
       // on below line adding click listener for save file button.
       saveFileBtn.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               // on below line we are checking if the edit text is empty or not.
               if (msgEdt.getText().toString().isEmpty()) {
                   // if the edit text is empty we are displaying a toast message.
                   Toast.makeText(MainActivity.this, "Please enter your message..", Toast.LENGTH_SHORT).show();
               } else {
                   // on below line checking for the file output stream.
                   try {
                       // on below line creating a file output stream.
                       FileOutputStream fos = new FileOutputStream(externalFile);
                       // on below line writing the data from edit text in file output stream/
                       fos.write(msgEdt.getText().toString().getBytes());
                       // on below line closing the file output stream.
                       fos.close();
                       // on below line displaying toast message as file has been saved.
                       Toast.makeText(MainActivity.this, "File saved to External Storage..", Toast.LENGTH_SHORT).show();
                       // on below line handling the exception.
                   } catch (IOException e) {
                       e.printStackTrace();
                   }
               }
           }
       });
       // on below line adding click listener for view file button.
       viewFileBtn.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               // on below line creating a string variable named as file data.
               String fileData = "";
               try {
                   // on below line creating a variable for file input stream and passing the file path to it.
                   FileInputStream fis = new FileInputStream(externalFile);
                   // on below line creating and initializing variable for data input stream.
                   DataInputStream in = new DataInputStream(fis);
                   // on below line creating and initializing variable for buffer reader.
                   BufferedReader br = new BufferedReader(new InputStreamReader(in));
                   // on below line reading the data from file and appending it to the file data variable.
                   String strLine;
                   while ((strLine = br.readLine()) != null) {
                       fileData = fileData + strLine;
                   }
                   // on below line setting data from variable to our text view.
                   dataTV.setText(fileData);
                   in.close();
                   // on below line handling the exception.
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
       });
   }
   // on below line creating a method to checking weather external storage is read only.
   private static boolean isExternalStorageReadOnly() {
       // on below line getting external storage and checking if it is media mounted read only.
       String extStorageState = Environment.getExternalStorageState();
       if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
           return true;
       }
       return false;
   }
   // on below line creating a method to check weather external storage is available or not.
   private static boolean isExternalStorageAvailable() {
       // on below line checking external storage weather it is available or not.
       String extStorageState = Environment.getExternalStorageState();
       if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
           return true;
       }
       return false;
   }
}

說明:在上面的程式碼中,首先我們為我們的EditText、按鈕和TextView建立變數。然後,我們建立一個變數來儲存外部檔案、檔名和檔案路徑作為字串變數。現在我們將看到onCreate方法。這是每個Android應用程式的預設方法。當應用程式檢視建立時,將呼叫此方法。在此方法中,我們設定內容檢視,即名為activity_main.xml的佈局檔案,以設定該檔案中的UI。在onCreate方法中,我們使用我們在activity_main.xml檔案中給出的ID來初始化按鈕、TextView和EditText變數。

之後,我們檢查裝置中是否存在外部儲存,以及我們是否具有讀取和寫入資料的許可權。如果使用者在裝置中存在外部儲存,則我們將使用檔案路徑和檔名初始化外部檔案變數。之後,我們為“儲存檔案”按鈕新增一個點選監聽器,在onClick方法中,我們檢查EditText欄位是否為空。如果EditText欄位不為空,則我們建立一個檔案輸出流並將文字輸入欄位中的資料儲存到該檔案中。

之後,我們為“檢視檔案”按鈕新增一個點選監聽器。在點選監聽器方法中,我們呼叫檔案輸入流來讀取我們儲存的檔案中的資料,並將該檔案中的資料設定到我們建立的TextView中。最後,我們建立了兩個方法,用於檢查外部儲存是否可用,以及我們是否可以讀取外部儲存。

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

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

輸出

結論

在本文中,我們探討了如何在Android中將檔案儲存到外部儲存。

更新於:2023年5月9日

3K+ 瀏覽量

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告