Hướng dẫn lập trình Android với bộ lưu trữ trong (Internal Storage)
Xem thêm các chuyên mục:
Android Internal Storage: Là nơi lưu trữ các dữ liệu cá nhân của từng ứng dụng, mà các dữ liệu này được lưu trữ và sử dụng cho riêng ứng dụng đó. Các ứng dụng khác không thể truy cập vào được. Thông thường khi ứng dụng bị gỡ bỏ khỏi thiết bị Android, các file dữ liệu liên quan cũng bị xóa bỏ theo.

Một đặc điểm nữa khi bạn làm việc với các file dữ liệu ở bộ nhớ trong bạn chỉ có thể làm việc với tên file đơn giản mà không thể làm việc với một tên file có đường dẫn.
Mở file ghi dữ liệu.
// Là một tên file đơn giản. // Chú ý!! Không cho phép đường dẫn. String simpleFileName ="note.txt"; // Mở một luồng ghi file. FileOutputStream out = openFileOutput(simpleFileName, MODE_PRIVATE);
Bạn có 4 lựa chọn chế độ ghi:
Chế độ tạo file | Mô tả |
MODE_PRIVATE | Đây là chế độ mặc định, file ghi ra chỉ được sử dụng bởi ứng dụng tạo ra nó, hoặc chia sẻ với cùng User ID. |
MODE_APPEND | Chế độ nối thêm dữ liệu vào file nếu nó đã tồn tại. |
MODE_ENABLE_WRITE_AHEAD_LOGGING | |
Các chế độ này rất nguy hiểm, nó giống như một lỗ hổng bảo mật trong Android, tốt nhất không nên sử dụng, bạn có thể sử dụng các kỹ thuật khác thay thế như:
|
|
Chế độ cho phép nhiều tiến trình (process) có thể ghi vào file. Tuy nhiên khuyến nghị không sử dụng chế độ này vì nó không làm việc trên một số phiên bản của Android. Bạn có thể sử dụng kỹ thuật khác để thay thế, chẳng hạn:
|
Mở file đọc dữ liệu:
// Là một tên file đơn giản. // Chú ý!! Không cho phép đường dẫn. String simpleFileName = "note.txt"; // Mở một luồng đọc file. FileInputStream in = this.openFileInput(simpleFileName);
Bây giờ bạn có thể làm một ví dụ ghi dữ liệu vào file lưu tại bộ nhớ trong, và đọc dữ liệu của file này.

Tạo một project có tên InternalStorageDemo.
- File > New > New Project > Empty Activity
- Name: InternalStorageDemo
- Package name: org.o7planning.internalstoragedemo
- Language: Java

Giao diện ứng dụng:

Giao diện của ứng dụng này rất đơn giản, nếu bạn quan tâm đến các bước để tạo ra nó hãy xem phần phụ lục phía cuối bài viết.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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"> <EditText android:id="@+id/editText" android:layout_width="0dp" android:layout_height="122dp" android:layout_marginStart="21dp" android:layout_marginLeft="21dp" android:layout_marginTop="20dp" android:layout_marginEnd="16dp" android:layout_marginRight="16dp" android:ems="10" android:inputType="textPersonName" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/button_save" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="44dp" android:text="Save to File" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/editText" /> <TextView android:id="@+id/textView" android:layout_width="0dp" android:layout_height="91dp" android:layout_marginStart="29dp" android:layout_marginLeft="29dp" android:layout_marginTop="29dp" android:layout_marginEnd="21dp" android:layout_marginRight="21dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/button_save" /> <Button android:id="@+id/button_read" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="38dp" android:text="Read File" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" /> </androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package org.o7planning.internalstoragedemo; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; public class MainActivity extends AppCompatActivity { private Button saveButton; private Button readButton; private TextView textView; private EditText editText; // Is a simple file name. // Note!! Do not allow the path. private String simpleFileName = "note.txt"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.saveButton = (Button) this.findViewById(R.id.button_save); this.readButton = (Button) this.findViewById(R.id.button_read); this.textView = (TextView) this.findViewById(R.id.textView); this.editText = (EditText) this.findViewById(R.id.editText); this.saveButton.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { saveData(); } }); this.readButton.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { readData(); } }); } private void saveData() { String data = this.editText.getText().toString(); try { // Open Stream to write file. FileOutputStream out = this.openFileOutput(simpleFileName, MODE_PRIVATE); // Ghi dữ liệu. out.write(data.getBytes()); out.close(); Toast.makeText(this,"File saved!",Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(this,"Error:"+ e.getMessage(),Toast.LENGTH_SHORT).show(); } } private void readData() { try { // Open stream to read file. FileInputStream in = this.openFileInput(simpleFileName); BufferedReader br= new BufferedReader(new InputStreamReader(in)); StringBuilder sb= new StringBuilder(); String s= null; while((s= br.readLine())!= null) { sb.append(s).append("\n"); } this.textView.setText(sb.toString()); } catch (Exception e) { Toast.makeText(this,"Error:"+ e.getMessage(),Toast.LENGTH_SHORT).show(); } } }
Sử dụng "Android Device Manager" bạn có thể xem được file đã được tạo ra trên hệ thống.

Xem thêm về công cụ "Device File Explorer":
Các bước để thiết kế giao diện của ứng dụng trong bài viết này:


Thêm Button "Save to File":


Thêm một TextView:


Thêm Button "Read File":


Sét đặt ID, Text cho các thành phần trên giao diện:
