我只需要下载图片,但问题是图片损坏了!!! 我找到了许多下载图像的方法,但仍然出现了这个问题。
我尝试这样做:
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file2 = new File(path,"DemoPictureX.png");
InputStream is=(InputStream) new URL("http://androidsaveitem.appspot.com/downloadjpg").getContent();
OutputStream os = new FileOutputStream(file2);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
我认为它只是从图像中读取了一行!!!
答案 0 :(得分:6)
你需要一个循环并从流中读取一个较小的缓冲区(如1024字节)。
URL url = new URL("your url here");
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
FileOutputStream fos = new FileOutputStream(targetFile);
byte buffer[] = new byte[1024];
int read;
while ((read = bis.read(buffer)) > 0) {
fos.write(buffer, 0, read);
}
fos.flush();
fos.close();
bis.close();
is.close();
这应该对你有用