ภาพรวม
ตัวอย่างนี้สาธิตวิธีดึงและแสดงพาธของ Cache Directory (ไดเรกทอรีแคช) ของแอปพลิเคชัน Android ปัจจุบัน โดยใช้ getCacheDir()
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio ไปที่ File → New Project กรอกรายละเอียดที่จำเป็นทั้งหมดเพื่อสร้างโปรเจกต์ใหม่
ขั้นตอนที่ 2: จัดทำ Layout (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:textSize="30sp"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
ขั้นตอนที่ 3: เขียนโค้ดหลัก (src/MainActivity.java)
package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@RequiresApi(api = Build.VERSION_CODES.P)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
// ดึงและแสดง Cache Directory Path
textView.setText("Cache Dir: " + getCacheDir().getAbsolutePath());
}
}
การทดสอบ
รันแอป จะแสดงพาธเช่น /data/user/0/com.example.myapplication/cache
โฟลเดอร์เก็บข้อมูลสำคัญใน Android
| เมธอด | พาธตัวอย่าง | ใช้สำหรับ | ถูกลบเมื่อ |
|---|---|---|---|
getCacheDir() | /data/user/0/pkg/cache | ไฟล์แคชชั่วคราว | ระบบต้องการพื้นที่ / Clear Cache |
getFilesDir() | /data/user/0/pkg/files | ไฟล์ถาวรของแอป | Uninstall แอป |
getExternalCacheDir() | /sdcard/Android/data/pkg/cache | แคชบน External Storage | ระบบต้องการพื้นที่ / Uninstall |
getExternalFilesDir() | /sdcard/Android/data/pkg/files | ไฟล์บน External Storage | Uninstall แอป |
การใช้งาน Cache Directory
1. เขียนไฟล์แคช
File cacheFile = new File(getCacheDir(), "temp_data.json");
try (FileOutputStream fos = new FileOutputStream(cacheFile)) {
fos.write(jsonData.getBytes());
}
2. อ่านไฟล์แคช
File cacheFile = new File(getCacheDir(), "temp_data.json");
if (cacheFile.exists()) {
String content = new String(Files.readAllBytes(cacheFile.toPath()));
}
3. ล้างแคชทั้งหมด
public void clearCache() {
File cacheDir = getCacheDir();
File[] files = cacheDir.listFiles();
if (files != null) {
for (File file : files) {
file.delete();
}
}
}
ข้อควรระวัง
- ระบบอาจลบไฟล์ใน Cache Dir ได้ทุกเมื่อเมื่อหน่วยความจำต่ำ
- ไม่ควรเก็บข้อมูลสำคัญที่ไม่สามารถสร้างใหม่ได้ใน Cache Dir
- ขนาดแคชมีจำกัด (ประมาณ 10-50MB ขึ้นอยู่กับอุปกรณ์)