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 に答える