Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 無需權限將文件保存到sdcard或應用緩存文件中

無需權限將文件保存到sdcard或應用緩存文件中

編輯:關於Android編程

Context的方法
getCacheDir
getFilesDir
getExternalCacheDir
getExternalFilesDir


特點1:無需權限將assets中的圖片文件保存到sdcard或內存中(當然資源是從網絡下載需添加網絡權限)
特點2:隨著應用卸載緩存數據也一並刪除
如果不想應用卸載也將相關資源卸載請保存到除此之外的其他目錄

目錄結構

\

 

activity_main.xml

 




    

    

    



 

MainActivity.java

 

package cn.weimei.tiankong.com.fileproject;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 調用方法=打印的路徑
 * getCacheDir=/data/user/0/cn.weimei.tiankong.com.fileproject/cache
 * getFilesDir=/data/user/0/cn.weimei.tiankong.com.fileproject/files
 * getExternalCacheDir=/storage/emulated/0/Android/data/cn.weimei.tiankong.com.fileproject/cache
 * getExternalFilesDir=/storage/emulated/0/Android/data/cn.weimei.tiankong.com.fileproject/files
 * 這幾個方法存儲無需權限
 */
public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private ImageView iv;
    private InputStream in;
    private WebView web;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        printdifrentPath();
        initView();
        //setImageViewByInputStrim();
        //loadImageByWebView();
        //saveAndLoadImgCacheDir();
        //saveAndLoadImgExternalCacheDir();
        //saveAndLoadFilesDir();
        //saveAndLoadExtranalFileDir();
        saveSdcardOrDataDir();
    }

    /**
     * 初始化視圖
     */
    private void initView() {
        iv = (ImageView) findViewById(R.id.iv);
        web = (WebView) findViewById(R.id.web);
    }

    /**
     * 將assets目錄的圖片加載到imageView中
     */
    private void setImageViewByInputStrim() {
        try {
            in = getAssets().open("12345.png");
        } catch (IOException e) {
            e.printStackTrace();
        }
        iv.setImageBitmap(BitmapFactory.decodeStream(in));
    }

    /**
     * 將assets目錄的圖片加載到WebView中
     */
    private void loadImageByWebView() {
        web.loadUrl("file:///android_asset/12345.png");
    }


    /**
     * 調用方法=打印的路徑
     * getCacheDir=/data/user/0/cn.weimei.tiankong.com.fileproject/cache
     * getFilesDir=/data/user/0/cn.weimei.tiankong.com.fileproject/files
     * getExternalCacheDir=/storage/emulated/0/Android/data/cn.weimei.tiankong.com.fileproject/cache
     * getExternalFilesDir=/storage/emulated/0/Android/data/cn.weimei.tiankong.com.fileproject/files
     * 這幾個方法存儲無需權限
     */
    public void printdifrentPath() {
        Log.d(TAG, "getCacheDir=" + getCacheDir());
        Log.d(TAG, "getFilesDir=" + getFilesDir());
        Log.d(TAG, "getExternalCacheDir=" + getExternalCacheDir());
        Log.d(TAG, "getExternalFilesDir=" + getExternalFilesDir(null));
    }

    /**
     * 將assets目錄的圖片保存到/data/user/0/cn.weimei.tiankong.com.fileproject/cache目錄下並顯示在imageView中
     */
    public void saveAndLoadCacheDir() {
        try {
            InputStream in = getAssets().open("12345.png");
            File filepath = getCacheDir();//getCacheDir
            File fileOut = new File(filepath.getPath(), "savecachedir.png");
            FileOutputStream os = new FileOutputStream(fileOut);
            byte[] buffer = new byte[1024];
            int count = 0;
            while ((count = in.read(buffer)) > 0) {
                os.write(buffer, 0, count);
            }
            //加載文件保存在cachedir的圖片
            iv.post(new Runnable() {
                @Override
                public void run() {
                    FileInputStream fileIs = null;
                    try {//getCacheDir
                        File loadFile = new File(getCacheDir().getPath() + "/savecachedir.png");
                        Log.d(TAG, "run: getCacheDir--path=" + loadFile.getPath());
                        fileIs = new FileInputStream(loadFile);
                        iv.setImageBitmap(BitmapFactory.decodeStream(fileIs));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 將assets目錄的圖片保存到/storage/emulated/0/Android/data/cn.weimei.tiankong.com.fileproject/cache目錄下並顯示在imageView中
     */
    public void saveAndLoadExternalCacheDir() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            try {
                InputStream in = getAssets().open("12345.png");
                File filepath = getExternalCacheDir();//getExternalCacheDir
                File fileOut = new File(filepath.getPath(), "saveextranalcachedir.png");
                FileOutputStream os = new FileOutputStream(fileOut);
                byte[] buffer = new byte[1024];
                int count = 0;
                while ((count = in.read(buffer)) > 0) {
                    os.write(buffer, 0, count);
                }
                //加載文件保存在cachedir的圖片
                iv.post(new Runnable() {
                    @Override
                    public void run() {
                        FileInputStream fileIs = null;
                        try {//getExternalCacheDir
                            //這樣也可以 File loadFile=new File(getExternalCacheDir().getPath()+"/saveextranalcachedir.png");
                            File loadFile = new File(getExternalCacheDir().getPath(), "saveextranalcachedir.png");
                            Log.d(TAG, "run: getExternalCacheDir--path=" + loadFile.getPath());
                            fileIs = new FileInputStream(loadFile);
                            iv.setImageBitmap(BitmapFactory.decodeStream(fileIs));
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }

        } else {
            Toast.makeText(this, "sdcard不存在", Toast.LENGTH_SHORT).show();
        }
    }
    /**
     * 將assets目錄的圖片保存到/data/user/0/cn.weimei.tiankong.com.fileproject/files目錄下並顯示在imageView中
     */
    public void saveAndLoadFilesDir() {
        try {
            InputStream is = getAssets().open("12345.png");
            File filepath = getFilesDir();//getFilesDir
            File fileOut = new File(filepath.getPath(), "saveandloadfiledir.png");
            FileOutputStream os = new FileOutputStream(fileOut);
            byte[] buffer = new byte[1024];
            int count = 0;
            while ((count = (is.read(buffer))) > 0) {
                os.write(buffer, 0, count);
            }
            //加載文件保存在filedir的圖片
            iv.post(new Runnable() {
                @Override
                public void run() {
                    FileInputStream fileIs = null;
                    try {//getFilesDir
                        //這樣也可以 File loadFile=new File(getFilesDir().getPath()+"/saveandloadfiledir.png");
                        File loadFile = new File(getFilesDir().getPath() + "/saveandloadfiledir.png");
                        Log.d(TAG, "run: getExternalCacheDir--path=" + loadFile.getPath());
                        fileIs = new FileInputStream(loadFile);
                        iv.setImageBitmap(BitmapFactory.decodeStream(fileIs));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 將assets目錄的圖片保存到/storage/emulated/0/Android/data/cn.weimei.tiankong.com.fileproject/files目錄下並顯示在imageView中
     */
    public void saveAndLoadExtranalFileDir() {
        try {
            InputStream is = getAssets().open("12345.png");
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                File outFile = new File(getExternalFilesDir(null).getPath(), "12345.png");
                FileOutputStream os = new FileOutputStream(outFile);
                int count = 0;
                byte[] buffer = new byte[1024];
                while ((count = (is.read(buffer))) > 0) {//注意buffer不要忘記了
                    os.write(buffer, 0, count);
                }
                iv.post(new Runnable() {
                    @Override
                    public void run() {
                        File loadFile = new File(getExternalFilesDir(null), "12345.png");
                        try {
                            Log.d(TAG, "run: getExternalFilesDir--path=" + loadFile.getPath());
                            FileInputStream is = new FileInputStream(loadFile);
                            iv.setImageBitmap(BitmapFactory.decodeStream(is));
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                });
            } else {
                Toast.makeText(this, "sdcard不存在", Toast.LENGTH_SHORT).show();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 如果不存在sdcard就保存到data目錄下
     */
    public void saveSdcardOrDataDir() {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            saveAndLoadExternalCacheDir(); //或者saveAndLoadExtranalFileDir();
        } else {
            saveAndLoadCacheDir();  //或者saveAndLoadFilesDir();
        }
    }
}


 

AndroidMenifest.xml

 




    
        
            
                

                
            
        
    



 

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved