我已经快速设计了一段代码,该代码从指定的URL加载,然后将其保存到SD卡,但是它没有保存到SD。
URL myFileUrl = new URL( Image_HTML);
String filepath = Environment.getExternalStorageDirectory().getAbsolutePath();
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bm = BitmapFactory.decodeStream(is);
FileOutputStream fos = new FileOutputStream(filepath+image_name);
bm.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
bm = BitmapFactory.decodeFile(filepath+image_name);
image_loader_view.setImageBitmap(bm);
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i("Hub", "FileNotFoundException: "+ e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.i("Hub", "IOException: "+ e.toString());
}
我试图让这段代码尽可能轻量级,并且我还激活了android清单中的EXTERNAL.STORAGE.WRITE。
答案 0 :(得分:1)
夫妻俩。
使用FileOutputStream时,必须确保在尝试向其写入文件之前创建要写入的目录。如果没有,你必须创建它。这可以通过mkdirs()
类的File
方法完成。
接下来由于Android使用的文件系统类型,我不确定是否需要调用getAbsolutePath
。我以前从未使用它来保存到SD。
我会尝试这些,看看其中一个是否会为你解决。