我在我的应用程序中实现缓存并将其部署在4.2.x设备上时遇到问题。
当我在app cache目录中保存文件时,我无法读取它。我使用具有root权限的文件管理器来浏览缓存文件夹,并且文件正确存在于我的缓存文件夹中,但是当我尝试读取它们时,获取文件未找到错误。
此问题仅与4.2 Android版本有关。在4.1-所有工作正常
这是我用来编写文件的代码
public static void writeFile(Bitmap bmp, File f) {
if (bmp == null)
return;
FileOutputStream out = null;
try {
out = new FileOutputStream(f);
boolean res = bmp.compress(Bitmap.CompressFormat.PNG, 80, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null)
out.close();
} catch (Exception ex) {
}
}
f.setReadable(true, false);
}
这是我构建文件对象的方式
File bitmapFile = new File(ImageManager.getInstance().getCacheDir(), key);
这是获取缓存路径的方法
if (Config.USE_INTERNAL_CACHE == false && sdState.equals(android.os.Environment.MEDIA_MOUNTED)) {
cacheDir = MyApp.getInstance().getExternalCacheDir();
} else {
cacheDir = MyApp.getInstance().getCacheDir();
}
if (!cacheDir.exists()) {
cacheDir.mkdirs();
}
此时我的文件被正确写入
/data/data/my.app.package/cache/
这是我用来读取文件的代码
public BitmapDrawable readFile(String fileName) {
FileInputStream in = null;
try {
in = new FileInputStream(getCacheDir()+"/"+fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bmp = BitmapFactory.decodeStream(in);
if (bmp == null) {
return null;
}
return new BitmapDrawable(MyApp.getInstance().getResources(), bmp);
}
这总是会产生此错误:
01-22 11:23:47.158: W/System.err(20660): java.io.FileNotFoundException: /data/data/my.app.package/cache/File Name: open failed: ENOENT (No such file or directory)
01-22 11:23:47.158: W/System.err(20660): at libcore.io.IoBridge.open(IoBridge.java:416)
01-22 11:23:47.158: W/System.err(20660): at java.io.FileInputStream.<init(FileInputStream.java:78)
01-22 11:23:47.158: W/System.err(20660): at java.io.FileInputStream.<init(FileInputStream.java:105)
01-22 11:23:47.158: W/System.err(20660): atmy.app.package.instanceManager.ImageManager.readFile(ImageManager.java:246)
01-22 11:23:47.158: W/System.err(20660): atmy.app.package.instanceManager.ImageManager$ImageQueueManager.run(ImageManager.java:186)
01-22 11:23:47.158: W/System.err(20660): at java.lang.Thread.run(Thread.java:856)
01-22 11:23:47.158: W/System.err(20660): Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
01-22 11:23:47.158: W/System.err(20660): at libcore.io.Posix.open(Native Method)
01-22 11:23:47.158: W/System.err(20660): atlibcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
01-22 11:23:47.158: W/System.err(20660): at libcore.io.IoBridge.open(IoBridge.java:400)
01-22 11:23:47.158: W/System.err(20660): ... 5 more
与此行相关:
in = new FileInputStream(getCacheDir()+"/"+fileName);
我已添加此权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
与此错误相关的路径和名称文件是正确的,文件存在于缓存文件夹中,为什么我无法读取它们? **我认为它可能是一个用户权限相关的问题,因为android 4.2中引入了新的多用户功能,但我无法弄明白。 **我也尝试设置文件.setReadable(true, false)
,但没有。感谢