Giới thiệu
Mỗi app Android có thư mục cache riêng biệt: /data/data/. Lấy đường dẫn tuyệt đối bằng getCacheDir().getAbsolutePath(). Hệ thống tự động xóa khi thiếu dung lượng.
Triển khai
Bước 1: Tạo dự án
Android Studio → New Project → Empty Activity.
Bước 2: Layout (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
android:padding="16dp"
android:gravity="center"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv_cache_path"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:lineSpacingExtra="4dp"
tools:text="Cache path will appear here" />
</LinearLayout>
Bước 3: MainActivity.java
package com.example.myapplication;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.TextView;
import java.io.File;
public class MainActivity extends AppCompatActivity {
TextView tvCachePath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvCachePath = findViewById(R.id.tv_cache_path);
// Lấy đường dẫn cache
File cacheDir = getCacheDir();
String cachePath = cacheDir.getAbsolutePath();
// Kiểm tra dung lượng
long freeSpace = cacheDir.getFreeSpace();
long totalSpace = cacheDir.getTotalSpace();
long usableSpace = cacheDir.getUsableSpace();
String info = "Cache Directory:\n" + cachePath +
"\n\nFree Space: " + formatSize(freeSpace) +
"\nTotal Space: " + formatSize(totalSpace) +
"\nUsable Space: " + formatSize(usableSpace) +
"\n\nExists: " + cacheDir.exists() +
"\nCan Write: " + cacheDir.canWrite();
tvCachePath.setText(info);
}
private String formatSize(long bytes) {
if (bytes < 1024) return bytes + " B";
int exp = (int) (Math.log(bytes) / Math.log(1024));
String unit = "KMGTPE".charAt(exp - 1) + "B";
return String.format("%.1f %s", bytes / Math.pow(1024, exp), unit);
}
}
Các thư mục quan trọng khác
| Phương thức | Đường dẫn típ thể | Đặc điểm |
|---|---|---|
| getCacheDir() | /data/data/pkg/cache/ | Hệ thống xóa khi thiếu RAM, không backup |
| getFilesDir() | /data/data/pkg/files/ | Lưu trữ bền vững, backup tự động |
| getExternalCacheDir() | /sdcard/Android/data/pkg/cache/ | Bên ngoài, có thể bị user xóa, không cần quyền |
| getExternalFilesDir() | /sdcard/Android/data/pkg/files/ | Bên ngoài, bị xóa khi uninstall app |
| Environment.getExternalStoragePublicDirectory() | /sdcard/Download, Pictures... | Công khai, cần quyền READ/WRITE_EXTERNAL_STORAGE (API<29) |
Best Practices
- Cache: Dữ liệu tạm, có thể tạo lại được (image cache, network response)
- Files: Dữ liệu quan trọng, user data, database, settings
- External: File lớn, chia sẻ với app khác, media
- Dọn dẹp: Giới hạn kích thước cache, xóa file cũ định kỳ
Ví dụ ghi/đọc file cache
// Ghi file cache File cacheFile = new File(getCacheDir(), "temp_data.json"); FileOutputStream fos = new FileOutputStream(cacheFile); fos.write(jsonData.getBytes()); fos.close(); // Đọc file cache FileInputStream fis = new FileInputStream(cacheFile); byte[] data = new byte[(int) cacheFile.length()]; fis.read(data); fis.close(); String json = new String(data);
Lưu ý: Từ Android 11 (API 30), quyền truy cập bộ nhớ ngoài bị hạn chế (Scoped Storage). Ưu tiên dùnggetCacheDir()vàgetFilesDir().