Android Đọc ghi file Cache

Code: Default | Auth: 03cd82

Hãy tham khảo bài viết này trước  https://zezo.dev/note/doc-ghi-file-o-bo-nho-trong

Bạn hãy sử dụng lại code ở bài viết trên để có sẵn EditText nhé. 

Bước 1: Trong layout bạn thêm 2 nút bấm

<Button 
android:id="@+id/btn_save_cache" 
android:layout_height="wrap_content" 
android:layout_width="wrap_content" 
android:onClick="SaveCache" 
android:text="Save to cache"/>

<Button
android:id="@+id/btn_read_cache" 
android:layout_height="wrap_content"
android:layout_width="wrap_content" 
android:onClick="ReadCache" 
android:text="Read from cache"/>

Bước 2: Viết code cho nút SaveCache (sự kiện onClick)

   public void SaveCache(View view){
        String file_name = "vd_cache.txt";
        String noi_dung = ed_content.getText().toString(); 
         // ed_content là EditText xem ở bài viết đọc ghi file ở link trên nhé

        try{
            // lấy đường dẫn thư mục cache
            File pathCacheDir = getCacheDir();
            // tạo file cache
            File objFile = new File(pathCacheDir, file_name);
            objFile.createNewFile(); // tạo mới file trống trong thư mục cache

            //----- tiến hành ghi vào file cache
            FileOutputStream fileOutputStream = new FileOutputStream(objFile.getAbsolutePath()); 
            fileOutputStream.write(noi_dung.getBytes());
            fileOutputStream.close();

            Toast.makeText(getBaseContext(),"Đã ghi vào cache", Toast.LENGTH_SHORT).show();
        }catch (IOException e){
            e.printStackTrace();
        }


    }

Bước 3: Viết code cho hàm ReadCache (sự kiện onClick)

    public void ReadCache(View view){
        String file_name = "vd_cache.txt";

        try {
            File pathCacheDir = getCacheDir();
            File objFile = new File(pathCacheDir,file_name);
            // tiến hành đọc file
            Scanner scanner = new Scanner(objFile);
            String tmp_data = "";
            while (scanner.hasNext()){
                tmp_data += scanner.nextLine();
            }
            scanner.close();

            Toast.makeText(getBaseContext(),"Nội dung cache: " + tmp_data, Toast.LENGTH_SHORT).show();

        }catch (IOException e){
            e.printStackTrace();
        }


    }

Kết quả:

Đọc ghi cache file