【发布时间】:2013-05-02 14:57:44
【问题描述】:
我目前正在尝试将文件保存在我的 android 应用程序的内部存储器中,但我无法正确地做到这一点!
这是我存储位图的方法:
private void storeBitmapInMemory(String id) throws IOException {
URL newurl = new URL(PictureUrl);
Bitmap bm = BitmapFactory.decodeStream(newurl.openConnection().getInputStream());
// The openfileOutput() method creates a file on the phone/internal storage in the context of your application
final FileOutputStream fos = context.openFileOutput(PREFIX + id +".jpeg", Context.MODE_PRIVATE);
// Use the compress method on the BitMap object to write image to the OutputStream
bm.compress(CompressFormat.JPEG, 100, fos);
}
当我执行此方法时一切看起来都很好,但实际上没有保存...当我尝试使用此方法从内存中读取文件时:
private Bitmap getStoredBitmapFromMemory(int idAvatar) {
File cacheDir = context.getCacheDir();
File f = new File(cacheDir, PREFIX + Integer.toString(idAvatar) + ".jpeg");
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return BitmapFactory.decodeStream(fis);
}
它抛出了这个异常:
05-02 10:50:22.487: W/System.err(25805): java.io.FileNotFoundException: /data/data/com.example.xxxx/cache/AVATAR_400021371.jpeg: open failed: ENOENT (No such file or directory)
05-02 10:50:22.497: W/System.err(25805): at libcore.io.IoBridge.open(IoBridge.java:416)
05-02 10:50:22.497: W/System.err(25805): at java.io.FileInputStream.<init>(FileInputStream.java:78)
05-02 10:50:22.497: W/System.err(25805): at com.example.xxxx.Performer.getStoredBitmapFromMemory(Performer.java:140)
我的 storeBitmapInMemory 有什么问题??
【问题讨论】:
-
你授权了吗?
-
您是否检查过 PREFIX 目录是否存在?在创建 FileOutputStream File dir = new File(PREFIX); 之前在 storeBitmapInMemory() 方法中执行此操作尝试导航到您认为文件在文件管理器中的位置,并在您花费太长时间尝试调试文件打开方法 if(!(dir.exists() && dir.isDirectory())) 目录之前检查它是否确实存在。 mkdirs();
-
你应该使用 openFileInput 来读取你使用 openFileOutput 存储的文件
-
抱歉,PREFIX 等于“AVATAR_”。这是我的文件名,例如:AVATAR_100234.jpeg(数字是 ID)。对于目录,我试图导航到我的应用程序的“数据”文件夹......但我的应用程序的包名称不在数据文件夹中......我不知道为什么......并且在我的异常错误路径是:/data/data(为什么有两个数据?fileexplorer 中只有一个...)。 com.example.xxxx 也不存在! :(