1. 程式人生 > 實用技巧 >Android開發筆記(二十一)——資料儲存之檔案儲存

Android開發筆記(二十一)——資料儲存之檔案儲存

檔案儲存是利用Java的I/O流來實現向Android硬體磁碟上進行讀寫的操作。

Android儲存概念

內部儲存 Internal Storage :不可更改的,隨著應用的解除安裝被刪除

內部儲存的特點:

  • 預設只能被建立它的應用訪問到
  • 當這個應用解除安裝後,內部儲存中的檔案也被刪除
  • 一旦內部儲存空間耗盡,手機也就無法使用

/data/data/<applicationId>/shard_prefs

/data/data/<applicationId>/databases

/data/data/<applicationId>/files

/data/data/<applicationId>/cache

這四個資料夾都是屬於內部儲存。

前兩個檔案是通過系統提供的類和方法來獲得檔案的內容。

後兩個檔案是通過 context.getCacheDir()context.getFilesDir() 這兩個方法來得到。

外部儲存 External Storage :可更改的。分為公有目錄和私有目錄,

公有目錄:通過 Environment.getExternalStoragePublicDirectory(int type) 方法來獲得公有目錄下對應型別的檔案。

私有目錄:隨著應用的解除安裝被刪除
/mnt/sdcard/data/data/<applicationId>/files

/mnt/sdcard/data/data/<applicationId>/cache

File內部儲存

比較重要的兩個類: FileOutputStreamFileInputStream

程式碼示例
FileActivity的java檔案:

public class FileActivity extends AppCompatActivity {

    private EditText mEtName;
    private Button mBtnSave,mBtnShow;
    private TextView mTvContent;

    private final String mFinalName = "text.txt";

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

        mEtName=findViewById(R.id.et_name);
        mBtnSave=findViewById(R.id.btn_save);
        mBtnShow=findViewById(R.id.btn_show);
        mTvContent=findViewById(R.id.tv_content);



        mBtnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save(mEtName.getText().toString().trim()); //trim()表示去除前後空格,沒有也可以
            }
        });

        mBtnShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTvContent.setText(read());
            }
        });
    }

    //儲存資料
    private void save(String content){
        FileOutputStream fileOutputStream=null;
        try {
            //建立儲存目標
            fileOutputStream = openFileOutput(mFinalName,MODE_PRIVATE);
            //位元組方式儲存方法
            fileOutputStream.write(content.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //關閉流
            if (fileOutputStream!=null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //讀取資料
    private String read(){
        FileInputStream fileInputStream = null;
        try {
            //獲取讀取檔案
            fileInputStream = openFileInput(mFinalName);
            //設定一次讀取位元組數
            byte[] buff = new  byte[1024];
            //獲取StringBuilder,實現字串拼接
            StringBuilder sb = new StringBuilder("");
            int len = 0;
            //迴圈讀取
            while ((len = fileInputStream.read(buff)) > 0){
                sb.append(new String(buff,0,len));
            }
            //返回讀取資料
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //關閉流
            if (fileInputStream!=null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}

佈局檔案

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="15dp">
    <EditText
        android:id="@+id/et_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="輸入內容"
        />
    <Button
        android:id="@+id/btn_save"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="儲存"
        android:layout_marginTop="10dp"
        />
    <Button
        android:id="@+id/btn_show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="顯示"
        android:layout_marginTop="10dp"
        />
    <TextView
        android:id="@+id/tv_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        />
</LinearLayout>

執行效果

總結

儲存資料:

  • 獲取FileOutputStream物件
  • 呼叫write()方法
  • 呼叫close()方法

讀取資料:

  • 獲取FileInputStream物件
  • 呼叫read()方法
  • 呼叫close()方法

File外部儲存