外部存儲 使用詳解

極力推薦文章:歡迎收藏
Android 乾貨分享 android

閱讀五分鐘,每日十點,和您一塊兒終身學習,這裏是程序員Android

本篇文章主要介紹 Android 開發中的部分知識點,經過閱讀本篇文章,您將收穫如下內容:程序員

  1. 保存外部存儲須要申請權限
  2. 外部存儲使用案例(保存,讀取,刪除圖片)

Android 設備支持外部存儲,好比SD卡等,保存在外部存儲的數據具備全局可讀性,可供在其餘設備好比電腦上閱讀,修改等。使用外部存儲須要獲取外部存儲的訪問權限<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />微信

1. 保存外部存儲須要申請權限

這個很重要,否則沒法操做SD 卡,佈局

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

2. 外部存儲使用案例(保存,讀取,刪除圖片)

  • 實現效果

外部存儲保存圖片的方法

判斷是否掛載 SD 卡方法

/**
     * 1.判斷SD卡是否掛載
     * **/
    public static boolean isMounted() {

        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);

    }
  • SD 保存圖片,刪除圖片、顯示圖片的方法

保存圖片到SD卡

保存圖片到SD卡 實現代碼以下:學習

// 保存圖片的方法
    public void BtnSaveImage(View view) {
        // 獲取圖片類型 bitmap
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                R.drawable.ic_launcher);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 將bitmap 壓縮成byte類型 並保存到outputstream中
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        bitmap.recycle();
        boolean saveimg = SaveImg(getApplicationContext(), "photo.png",
                baos.toByteArray());
        if (saveimg) {
            Toast.makeText(getApplicationContext(), "保存成功" + store_path,
                    Toast.LENGTH_SHORT).show();
        }
        try {
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 保存圖片的方法
    public static boolean SaveImg(Context context, String filename, byte[] data) {
        // 判斷是否掛載SD卡
        if (!isMounted()) {
            Toast.makeText(context, "SD卡未安裝", Toast.LENGTH_SHORT).show();
            return false;
        }
        File dir = new File(store_path);
        // 建立文件目錄
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            // 向文件目錄 dir中寫文件filename
            FileOutputStream fos = new FileOutputStream(new File(dir, filename));
            fos.write(data);
            fos.close();
            return true;

        } catch (IOException e) {
            e.printStackTrace();
            Log.i("TAG", "IOException..." + e);
            return false;
        }
    }

刪除圖片的方法

刪除圖片 代碼實現代碼實現以下:spa

public void BtnDeleteImage(View view) {
        DeletleImg(getApplicationContext(), "photo.png");

    }

    // 刪除圖片
    public static void DeletleImg(Context context, String filename) {

        File dirfile = new File(store_path + filename);
        // 判斷文件是否存在
        if (!dirfile.exists()) {
            Toast.makeText(context, "文件不存在", Toast.LENGTH_SHORT).show();
            return;
        }
        if (dirfile.isDirectory()) {
            String[] childdir = dirfile.list();
            for (int i = 0; i < childdir.length; i++) {
                new File(dirfile, childdir[i]).delete();
            }
        }
        dirfile.delete();
    }

讀取顯示圖片的方法

讀取顯示圖片代碼實現以下:code

// 讀取圖片
    public void BtnReadImage(View view) {
        Bitmap readImg = ReadImg(getApplicationContext(), "photo.png");
        if (readImg == null) {
            Toast.makeText(getApplicationContext(), "讀取失敗" + store_path,
                    Toast.LENGTH_SHORT).show();
        } else {
            ((ImageView) findViewById(R.id.img_external))
                    .setImageBitmap(readImg);
        }

    }

    // 讀取圖片
    public static Bitmap ReadImg(Context context, String filename) {
        // 判斷是否掛載SD卡
        if (!isMounted()) {
            Toast.makeText(context, "SD卡未安裝", Toast.LENGTH_SHORT).show();
            return null;
        }
        // 獲取文件路徑下的文件名稱
        File imgFile = new File(store_path, filename);
        if (imgFile.exists()) {
            Log.i("TAG", "imgFile" + imgFile.getAbsolutePath());
            // 將路徑下的文件轉換成 bitmap
            return BitmapFactory.decodeFile(imgFile.getAbsolutePath());
        } else {
            Toast.makeText(context, "文件不存在", Toast.LENGTH_SHORT).show();
        }

        return null;
    }
  • 佈局以下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/img_external"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btn_external_save"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="BtnSaveImage"
        android:text="保存圖片到SD卡" />

    <Button
        android:id="@+id/btn_external_delete"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="BtnDeleteImage"
        android:text="刪除SD卡 圖片" />

    <Button
        android:id="@+id/btn_external_read"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="BtnReadImage"
        android:text="顯示SD卡 圖片" />

</LinearLayout>

至此,本篇已結束,若有不對的地方,歡迎您的建議與指正。同時期待您的關注,感謝您的閱讀,謝謝!orm

微信關注公衆號:  程序員Android,領福利

相關文章
相關標籤/搜索