Hôm nay chúng ta sẽ tìm hiểu về lưu trữ nội bộ trong Android.
Android cung cấp một số phương thức có cấu trúc để lưu trữ dữ liệu, bao gồm:
- Shared Preferences (Tùy chọn chia sẻ)
- Internal Storage (Lưu trữ nội bộ)
- External Storage (Lưu trữ ngoài)
- SQLite Storage (Lưu trữ bằng SQLite)
- Lưu trữ qua kết nối mạng (trên nền tảng đám mây)
Trong hướng dẫn này, chúng ta sẽ tìm hiểu cách lưu và đọc dữ liệu từ tệp bằng Android Internal Storage.
Lưu trữ nội bộ trong Android
Lưu trữ nội bộ trong Android là hình thức lưu trữ dữ liệu riêng tư trên bộ nhớ thiết bị. Theo mặc định, việc lưu và đọc tệp trong bộ nhớ nội bộ là riêng tư đối với ứng dụng – các ứng dụng khác sẽ không thể truy cập vào các tệp này. Khi người dùng gỡ cài đặt ứng dụng, các tệp đã lưu trong bộ nhớ nội bộ liên quan đến ứng dụng đó cũng sẽ bị xóa.
Tuy nhiên, cần lưu ý rằng một số người dùng có thể root điện thoại Android của họ, từ đó có quyền truy cập ở cấp độ siêu người dùng (superuser). Những người dùng này có thể đọc và ghi bất kỳ tệp nào họ muốn.
Thao tác đọc và ghi tệp văn bản trong Bộ nhớ trong Android
Android cung cấp hai phương thức openFileInput
và openFileOutput
từ các lớp Java I/O để thao tác đọc và ghi dữ liệu từ các tệp cục bộ.
openFileOutput()
: Phương thức này được dùng để tạo và lưu một tệp. Cú pháp của nó như sau:
FileOutputStream fOut = openFileOutput("file name",Context.MODE_PRIVATE);
Phương thức openFileOutput()
trả về một thể hiện của FileOutputStream
. Sau đó, chúng ta có thể gọi phương thức write
để ghi dữ liệu vào tệp. Cú pháp được trình bày dưới đây:
String str = "test data";
fOut.write(str.getBytes());
fOut.close();
openFileInput()
: Phương thức này được sử dụng để mở một tệp và đọc nội dung từ tệp đó. Nó trả về một thể hiện của FileInputStream
. Cú pháp được trình bày dưới đây:
FileInputStream fin = openFileInput(file);
Sau đó, chúng ta gọi phương thức read
để đọc từng ký tự một từ tệp và sau đó in ra. Cú pháp được trình bày dưới đây:
int c;
String temp="";
while( (c = fin.read()) != -1){
temp = temp + Character.toString((char)c);
}
fin.close();
Trong đoạn mã trên, chuỗi temp
chứa toàn bộ dữ liệu của tệp.
Lưu ý rằng các phương thức này không chấp nhận đường dẫn tệp (ví dụ: path/to/file.txt
), chúng chỉ nhận tên tệp đơn giản.
Cấu trúc dự án sử dụng bộ nhớ trong Android
Ví dụ mã nguồn lưu trữ nội bộ trên Android
Tệp giao diện XML bao gồm một EditText
để nhập dữ liệu ghi vào tệp, cùng với một nút Write
và một nút Read
.
Lưu ý rằng các phương thức onClick
được khai báo trực tiếp trong tệp XML như minh họa bên dưới: activity_main.xml
<RelativeLayout xmlns:android="<https://schemas.android.com/apk/res/android>"
xmlns:tools="<https://schemas.android.com/tools>"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:padding="5dp"
android:text="Android Read and Write Text from/to a File"
android:textStyle="bold"
android:textSize="28sp" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/textView1"
android:layout_marginTop="22dp"
android:minLines="5"
android:layout_margin="5dp">
<requestFocus />
</EditText>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Write Text into File"
android:onClick="WriteBtn"
android:layout_alignTop="@+id/button2"
android:layout_alignRight="@+id/editText1"
android:layout_alignEnd="@+id/editText1" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Read Text From file"
android:onClick="ReadBtn"
android:layout_centerVertical="true"
android:layout_alignLeft="@+id/editText1"
android:layout_alignStart="@+id/editText1" />
</RelativeLayout>
MainActivity
chứa phần triển khai chức năng đọc và ghi dữ liệu vào tệp như đã trình bày ở trên.
package com.journaldev.internalstorage;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class MainActivity extends Activity {
EditText textmsg;
static final int READ_BLOCK_SIZE = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textmsg=(EditText)findViewById(R.id.editText1);
}
// write text to file
public void WriteBtn(View v) {
// add-write text into file
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(textmsg.getText().toString());
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
// Read text from file
public void ReadBtn(View v) {
//reading text from file
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
textmsg.setText(s);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Tại đây, một thông báo dạng Toast sẽ được hiển thị khi dữ liệu được ghi thành công vào bộ nhớ trong, và khi đọc dữ liệu từ tệp, nội dung sẽ được hiển thị ngay trong chính EditText
.
Hình ảnh bên dưới là kết quả đầu ra của dự án. Hình minh họa cho thấy văn bản được ghi vào bộ nhớ trong và khi nhấn nút Read
, nội dung đó sẽ hiển thị lại trong cùng một EditText
.
Tệp được lưu ở đâu?
Để xem trực tiếp tệp, hãy mở Android Device Monitor từ Tools → Android → Android Device Monitor. Tệp sẽ nằm trong thư mục: data → data → {tên gói ứng dụng} → files
như hiển thị trong hình bên dưới.
Tệp “mytextfile.txt” được tìm thấy trong thư mục có tên gói của dự án, tức là com.journaldev.internalstorage
, như hiển thị bên dưới.
Tải xuống dự án hoàn chỉnh cho ví dụ về lưu trữ bộ nhớ trong của Android từ liên kết bên dưới.