Quantcast
Channel: CSDN博客移动开发推荐文章
Viewing all articles
Browse latest Browse all 5930

无需权限将文件保存到sdcard或应用缓存文件中

$
0
0
Context的方法
getCacheDir
getFilesDir
getExternalCacheDir

getExternalFilesDir


特点1:无需权限将assets中的图片文件保存到sdcard或内存中(当然资源是从网络下载需添加网络权限)
特点2:随着应用卸载缓存数据也一并删除
如果不想应用卸载也将相关资源卸载请保存到除此之外的其他目录

目录结构



activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="cn.weimei.tiankong.com.fileproject.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/textView" />

    <ImageView
        android:id="@+id/iv"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_below="@+id/textView" />

    <WebView
        android:id="@+id/web"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_below="@+id/iv" />
</RelativeLayout>


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

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.weimei.tiankong.com.fileproject">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        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>


源码下载:http://download.csdn.net/detail/u013042707/9645244



作者:u013042707 发表于2016/10/3 17:16:09 原文链接
阅读:89 评论:0 查看评论

Viewing all articles
Browse latest Browse all 5930

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>