我正在尝试创建一个在sd卡上保存临时文件的应用程序。
如果用户没有SD卡,我希望应用程序将文件保存在内部存储
中我的英语。
答案 0 :(得分:4)
这是我在SD卡或内部存储上使用的缓存,但要小心。您必须定期清除缓存,尤其是内部存储。
private static boolean sIsDiskCacheAvailable = false;
private static File sRootDir = null;
public static void initializeCacheDir(Context context){
Context appContext = context.getApplicationContext();
File rootDir = null;
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
// SD card is mounted, use it for the cache
rootDir = appContext.getExternalCacheDir();
} else {
// SD card is unavailable, fall back to internal cache
rootDir = appContext.getCacheDir();
if(rootDir == null){
sIsDiskCacheAvailable = false;
return;
}
}
sRootDir = rootDir;
// If the app doesn't yet have a cache dir, create it
if(sRootDir.mkdirs()){
// Create the '.nomedia' file, to prevent the mediastore from scanning your temp files
File nomedia = new File(sRootDir.getAbsolutePath(), ".nomedia");
try{
nomedia.createNewFile();
} catch(IOException e){
Log.e(ImageCache.class.getSimpleName(), "Failed creating .nomedia file!", e);
}
}
sIsDiskCacheAvailable = sRootDir.exists();
if(!sIsDiskCacheAvailable){
Log.w(ImageCache.class.getSimpleName(), "Failed creating disk cache directory " + sRootDir.getAbsolutePath());
} else {
Log.d(ImageCache.class.getSimpleName(), "Caching enabled in: " + sRootDir.getAbsolutePath());
// The cache dir is created, you can use it to store files
}
}
答案 1 :(得分:0)
您可以使用Context的getExternalCacheDir()方法获取File引用,您可以在其中存储SD卡上的文件。当然,您必须像往常一样进行常规检查以确保外部存储是可挂载和可写的,但这可能是存储该类型临时文件的最佳位置。您可能想要做的一件事就是设置可以在缓存目录中使用的最大空间量,然后,只要您需要编写新的临时文件,如果该文件超过最大空间,则开始删除临时文件,从最旧的文件开始,直到有足够的空间。 或者,也许这样的事情可行:
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File externalRoot = Environment.getExternalStorageDirectory();
File tempDir = new File(externalRoot, ".myAppTemp");
}
预先加上"。"应该隐藏文件夹,我很确定。