2

只是我需要下载图像,但问题是图像损坏了!!!我找到了很多下载图像的方法,但仍然出现了这个问题。

我试着这样做:

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();

我认为它只是从图像中读取了一些行!!!!

4

1 回答 1

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();

这应该适合你

于 2012-06-13T09:14:36.173 回答