• Android Video Tutorials

Android - 內部儲存



Android 為應用程式提供多種儲存方式來儲存其資料。這些儲存位置包括共享首選項、內部和外部儲存、SQLite 儲存以及透過網路連線進行儲存。

本章我們將瞭解內部儲存。內部儲存是在裝置記憶體中儲存私有資料。

預設情況下,這些檔案是私有的,只能被您的應用程式訪問,並且在使用者刪除您的應用程式時會被刪除。

寫入檔案

為了使用內部儲存將一些資料寫入檔案,請使用檔名和模式呼叫 openFileOutput() 方法。模式可以是 private、public 等。其語法如下:

FileOutputStream fOut = openFileOutput("file name here",MODE_WORLD_READABLE);

openFileOutput() 方法返回 FileOutputStream 的一個例項。因此,您可以在 FileInputStream 物件中接收它。之後,您可以呼叫 write 方法將資料寫入檔案。其語法如下:

String str = "data";
fOut.write(str.getBytes());
fOut.close();

讀取檔案

為了讀取您剛剛建立的檔案,請使用檔名呼叫 openFileInput() 方法。它返回 FileInputStream 的一個例項。其語法如下:

FileInputStream fin = openFileInput(file);

之後,您可以呼叫 read 方法一次讀取一個字元,然後列印它。其語法如下:

int c;
String temp="";
while( (c = fin.read()) != -1){
   temp = temp + Character.toString((char)c);
}

//string temp contains all the data of the file.
fin.close();

除了 write 和 close 方法外,FileOutputStream 類還提供其他方法來更好地寫入檔案。這些方法列在下面:

序號 方法及說明
1

FileOutputStream(File file, boolean append)

此方法構造一個新的 FileOutputStream,該方法寫入檔案。

2

getChannel()

此方法返回一個只寫 FileChannel,它與該流共享其位置。

3

getFD()

此方法返回底層檔案描述符。

4

write(byte[] buffer, int byteOffset, int byteCount)

此方法將從位元組陣列緩衝區中從偏移量位置開始的 count 個位元組寫入此流。

除了 read 和 close 方法外,FileInputStream 類還提供其他方法來更好地讀取檔案。這些方法列在下面:

序號 方法及說明
1

available()

此方法返回可以讀取或跳過而不阻塞更多輸入的位元組數的估計值。

2

getChannel()

此方法返回一個只讀 FileChannel,它與該流共享其位置。

3

getFD()

此方法返回底層檔案描述符。

4

read(byte[] buffer, int byteOffset, int byteCount)

此方法最多從此流中讀取 length 個位元組,並將它們儲存在從 offset 開始的位元組陣列 b 中。

示例

這是一個演示使用內部儲存來儲存和讀取檔案的示例。它建立一個基本的儲存應用程式,允許您讀取和寫入內部儲存。

要試用此示例,您可以在實際裝置或模擬器上執行它。

步驟 描述
1 您將使用 Android Studio IDE 在包 com.example.sairamkrishna.myapplication 下建立一個 Android 應用程式。
2 修改 src/MainActivity.java 檔案以新增必要的程式碼。
3 修改 res/layout/activity_main 以新增相應的 XML 元件。
4 執行應用程式,選擇正在執行的 Android 裝置,將應用程式安裝在其上並驗證結果。

以下是修改後的主活動檔案 src/MainActivity.java 的內容。

package com.example.sairamkrishna.myapplication;

import android.app.Activity;
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 java.io.FileInputStream;
import java.io.FileOutputStream;

public class MainActivity extends Activity  {
   Button b1,b2;
   TextView tv;
   EditText ed1;

   String data;
   private String file = "mydata";

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      b1=(Button)findViewById(R.id.button);
      b2=(Button)findViewById(R.id.button2);

      ed1=(EditText)findViewById(R.id.editText);
      tv=(TextView)findViewById(R.id.textView2);
      b1.setOnClickListener(new View.OnClickListener() {
         
         @Override
         public void onClick(View v) {
            data=ed1.getText().toString();
            try {
               FileOutputStream fOut = openFileOutput(file,MODE_WORLD_READABLE);
               fOut.write(data.getBytes());
               fOut.close();
               Toast.makeText(getBaseContext(),"file saved",Toast.LENGTH_SHORT).show();
            }
            catch (Exception e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
            }
         }
      });

      b2.setOnClickListener(new View.OnClickListener() {
         
         @Override
         public void onClick(View v) {
            try {
               FileInputStream fin = openFileInput(file);
               int c;
               String temp="";
               while( (c = fin.read()) != -1){
                  temp = temp + Character.toString((char)c);
               }
               tv.setText(temp);
               Toast.makeText(getBaseContext(),"file read",Toast.LENGTH_SHORT).show();
            }
            catch(Exception e){
            }
         }
      });
   }
}

以下是修改後的 xml 檔案 res/layout/activity_main.xml 的內容。

在以下程式碼中,abc 表示 tutorialspoint.com 的徽標。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
   android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
      
   <TextView android:text="Internal storage" android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/textview"
      android:textSize="35dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point"
      android:id="@+id/textView"
      android:layout_below="@+id/textview"
      android:layout_centerHorizontal="true"
      android:textColor="#ff7aff24"
      android:textSize="35dp" />
   
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Save"
      android:id="@+id/button"
      android:layout_alignParentBottom="true"
      android:layout_alignLeft="@+id/textView"
      android:layout_alignStart="@+id/textView" />
      
   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText"
      android:hint="Enter Text"
      android:focusable="true"
      android:textColorHighlight="#ff7eff15"
      android:textColorHint="#ffff25e6"
      android:layout_below="@+id/imageView"
      android:layout_alignRight="@+id/textView"
      android:layout_alignEnd="@+id/textView"
      android:layout_marginTop="42dp"
      android:layout_alignLeft="@+id/imageView"
      android:layout_alignStart="@+id/imageView" />
      
   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="load"
      android:id="@+id/button2"
      android:layout_alignTop="@+id/button"
      android:layout_alignRight="@+id/editText"
      android:layout_alignEnd="@+id/editText" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Read"
      android:id="@+id/textView2"
      android:layout_below="@+id/editText"
      android:layout_toLeftOf="@+id/button2"
      android:layout_toStartOf="@+id/button2"
      android:textColor="#ff5bff1f"
      android:textSize="25dp" />
      
</RelativeLayout>

以下是 res/values/string.xml 的內容。

<resources>
   <string name="app_name">My Application</string>
</resources>

以下是 AndroidManifest.xml 檔案的內容。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sairamkrishna.myapplication" >
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name=".MainActivity"
         android:label="@string/app_name" >
         
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
         
      </activity>
      
   </application>
</manifest>

讓我們嘗試執行我們剛剛修改的 Storage 應用程式。我假設您在進行環境設定時建立了您的 AVD。要從 Android Studio 執行應用程式,請開啟專案中的一個活動檔案,然後單擊工具欄中的執行 Eclipse Run Icon 圖示。Android Studio 將應用程式安裝到您的 AVD 並啟動它,如果您的設定和應用程式一切正常,它將顯示以下模擬器視窗:

Android Internal Stroage Tutorial

現在您需要做的就是在欄位中輸入任何文字。例如,我輸入了一些文字。按儲存按鈕。以下通知將出現在您的 AVD 中:

Android Internal Stroage Tutorial

現在,當您按下載入按鈕時,應用程式將讀取檔案並顯示資料。在我們的例子中,將返回以下資料:

Android Internal Stroage Tutorial

請注意,您可以透過切換到 DDMS 選項卡來實際檢視此檔案。在 DDMS 中,選擇檔案瀏覽器並導航到此路徑。

tools>android>android device Monitor

這也在下面的圖片中顯示。

Android Internal Stroage Tutorial
廣告