Android Đọc ghi file ở bộ nhớ ngoài

Code: Default | Auth: 03cd82

Phân biệt bộ nhớ trong và bộ nhớ ngoài

Bạn tham khảo tại https://zezo.dev/note/doc-ghi-file-o-bo-nho-trong

Bước 1: Tạo ứng dụng mới hoặc activity mới ở ứng dụng trước

Bước 2: Trong layout tạo 2 nút bấm

<button 
android:id="@+id/btn_save_sdcard"
android:layout_height="wrap_content"
 android:layout_width="wrap_content" 
android:onClick="SaveFileSDCard" 
android:text="Save to file SD Card"/>

<button 
android:id="@+id/btn_read_sdcard" 
android:layout_height="wrap_content" 
android:layout_width="wrap_content" 
android:onClick="ReadFileSDCard" 
android:text="Read from file  SD Card">

Bước 3: Viết code cho hàm SaveFileSDCard (là sự kiện onClick nút bấm nhé)

 public void SaveFileSDCard(View view){
        String data = "Xin chao, noi dung ghi sdcard"; // nội dung cần ghi vào file, bạn có thể lấy từ EditText
        //---------- Ghi file
        // khai báo đường dẫn tới file ở thẻ SDcard
        String sdcard_file = Environment.getExternalStorageDirectory().getAbsolutePath() + "/hello.txt";
        
     
        try {
            // tạo đối tượng outputstream 
            FileOutputStream fileOutputStream = new FileOutputStream(sdcard_file);

            // tạo luồng ghi
            OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream);

            writer.write(data);
            writer.close(); // đóng luồng ghi
            fileOutputStream.close();
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Bước 4: Viết code cho hàm ReadFileSDCard (là sự kiện onClick nút bấm nhé)

   public void ReadFileSDCard(View view){

        String sdcard_file = Environment.getExternalStorageDirectory().getAbsolutePath() + "/hello.txt";

        // Đọc thẻ nhớ
        File file_to_read = new File(sdcard_file);
        try {
            // dùng đối tượng scanner để đọc file
            Scanner scanner = new Scanner( file_to_read   );

            String tmp_data = "";

            while (scanner.hasNext()){
                tmp_data += scanner.nextLine();  // đọc giống trong java thuần
            }

            scanner.close(); // đọc xong thì đóng luồng và thông báo nội dung ra màn hình

            Toast.makeText(getBaseContext(),tmp_data,Toast.LENGTH_SHORT).show();

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

Bước 5: Đừng quên xin quyền đọc ghi file

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Chỗ khai báo trong manifest như sau (Bạn chỉ quan tâm tới 2 dòng khai báo quyền thôi nhé):


 
<manifest package="com.spx.docghifile" xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application 
android:allowbackup="true" 
android:icon="@mipmap/ic_launcher" 
android:label="@string/app_name" 
android:roundicon="@mipmap/ic_launcher_round" 
android:supportsrtl="true" 
android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER"/>
          
          </intent-filter>
        </activity>
    </application> 
</manifest>

 

Bước 6: Chạy ứng dụng sau đó đóng hết các cửa sổ trên điện thoại, vào phần info của ứng dụng để cấp quyền đọc ghi sdcard rồi chạy lại ứng dụng để thực hiện bấm ghi và đọc

Cấp quyền đọc ghi file

Kết quả chạy như sau:

Ghi file sdcard