背景
如果我们有需要在应用缓存目录下、Application的onCreate()中创建文件夹,按老方法是不行的
public class MyApplication extends Application {@Overridepublic void onCreate() {super.onCreate();String path = Environment.getExternalStorageDirectory() + "/" + getPackageName() + "/cache/my-cache/Bayern/Muller";File file = new File(path);while (!file.exists()) {file.mkdirs();}}
}
会发现file.mkdirs()之后,file.exist()依旧是false,文件依旧不存在(即便加了权限也是如此),这是个角度刁钻的神坑
解决方案
只需要把缓存路径换成api的调用就行了
public class MyApplication extends Application {@Overridepublic void onCreate() {super.onCreate();String path = getApplicationContext().getCacheDir()+"/my-cache/Bayern/Muller"; //File file = new File(path);while (!file.exists()) {file.mkdirs();}}
}