我正在尝试保存已保存到SD卡的下载文件的路径,但是当我尝试检索它时遇到了麻烦。当我尝试将其转换为Bitmap时,它表示无法找到该文件,即使它位于SD卡上。
文件示例:/storage/emulated/0/_1404876264453.jpeg
以下是我用来下载照片并将其存储到SD卡的代码(返回保存在设备上的URL):
private String downloadProfile(String url)
{
String imageUrl = null;
try
{
String PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
String mimeType = getMimeType(url);
String fileExtension = "."+mimeType.replace("image/", "");
URL u = new URL(url);
HttpURLConnection con = (HttpURLConnection) u.openConnection();
con.setRequestMethod("GET");
con.setDoInput(true);
con.connect();
long millis=System.currentTimeMillis();
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "_"+millis);
FileOutputStream f = new FileOutputStream(outputFile);
InputStream in = con.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read()) > 0){
f.write(buffer, 0, len1);
}
imageUrl = outputFile.getAbsolutePath()+fileExtension;
f.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return imageUrl;
}
下载后,我将上面的URL插入到SQLite数据库中;它储存很好。我使用Astro文件管理器检查文件是否在那里,它是。
这是我的BaseAdapter中的代码,它接受上面的文件url并尝试将其转换为Bitmap:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
String profilePath = result_pos.get("profile_url"); // this just returns the example url
Bitmap bitmap = BitmapFactory.decodeFile(profilePath, options);
imageView.setImageBitmap(bitmap);
LogCat:
07-08 23:35:17.660: E/BitmapFactory(25463): Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/_1404876264453.jpeg: open failed: ENOENT (No such file or directory)
答案 0 :(得分:2)
检查此链接。我希望它对您有用。 reference link
1)create your own folder and save image name in proper way.
2)save image path in sqlite database
3)retrieve same path for get images.