安卓(Android) 怎么获取外部缓存目录

2019年10月18日21:53:05安卓(Android) 怎么获取外部缓存目录已关闭评论 301 1358字阅读4分31秒

1.简介

安卓(Android) 怎么获取外部缓存目录?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

 

import java.io.File;
import java.io.IOException;
import android.content.Context;
import android.os.Environment;

import android.util.Log;

public class Main {
    private static final String NOMEDIA_FILENAME = ".nomedia";
    private static final String TAG = "FileCacheUtil";

    public static File getExternalCacheDir(Context context) {
        return getExternalStorageDir(context, "/cache");
    }

    
    private static File getExternalStorageDir(Context context, String dir) {
        if (dir != null) {
            File extMediaDir = new File(
                    Environment.getExternalStorageDirectory()
                            + "/Android/data/" + context.getPackageName()
                            + dir);

            if (extMediaDir.exists()) {
                createNomediaDotFile(context, extMediaDir);
                return extMediaDir;
            }

            if (isSdCardWritable()) {
                extMediaDir.mkdirs();
                createNomediaDotFile(context, extMediaDir);
                return extMediaDir;
            } else {
                Log.e(TAG,
                        "SD card not writeable, unable to create directory: "
                                + extMediaDir.getPath());
            }
        }
        return null;
    }

    private static void createNomediaDotFile(Context context, File directory) {
        if (directory != null && isSdCardWritable()) {
            File nomedia = new File(directory, NOMEDIA_FILENAME);

            if (nomedia != null && !nomedia.exists()) {
                try {
                    nomedia.mkdirs();
                    nomedia.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e(TAG, "unable to create .nomedia file in "
                            + directory.getPath(), e);
                }
            }
        }
    }

    
    public static boolean isSdCardWritable() {
        return Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState());
    }
}

 
继续阅读
编程十万个怎么办