如何下载图像和存储在Android中的SD卡?

时间:2012-06-21 12:15:24

标签: android android-image

我准备了从服务器下载图像和存储在sdcard中的代码。为此我准备了代码,

 URL url;
 try {
     url = new URL("http://myserver_path/applikaza/appstore/apks/ScrResoluton/scrresolution.jpg");
     input = url.openStream();
     String storagePath = Environment.getExternalStorageDirectory().toString();
     String basepath = storagePath + "/Guayama/" + folderName;
     output = new FileOutputStream(basepath + "/home.png");
     byte[] buffer = new byte[5000];

     int bytesRead = 0;
     while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
         output.write(buffer, 0, bytesRead);
     }

 } catch (MalformedURLException e) { // TODO Auto-generated catch block
     e.printStackTrace();
 } finally {
     output.close();
     input.close();
 }   

但在output.close()得到NullPointerException。我认为在某些地方做错了。请帮助我。

1 个答案:

答案 0 :(得分:0)

您在output.close()处获得NullPointerException的原因是您的URL格式不正确。对于初学者,它不包含有效的协议。这将导致在行上抛出MalformedURLException

url = new URL("E:/Suresh/images/home.png");

然后你会直接进入catch块,然后是finally块,它调用output.close(),但输出为空行

output = new FileOutputStream(basepath + "/home.png");

从未被执行过。

您需要更正您的网址(请参阅说明here)并且您需要更正您的异常处理,例如MalformedURLException,这只会在您设置网址的值时被抛出,并且因此,当执行“finally”块时,输出或输入永远不会有非空值。

您的网址可能应为“http://something/Suresh/images/home.png”或“file://something/Suresh/images/home.png”。如果home.png文件位于Android设备的另一台计算机上,请尝试通过Web浏览器访问它,并使用网络浏览器显示的URL和“http://”。

相关问题