2

simply i need to download an image but the problem is the image get corrupted !!! i find many way to download the image but still this problem appeared .

i try do this :

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

i think it read just read some row from the image !!!

Praveenkumar
  • 24,084
  • 23
  • 95
  • 173
Hanaa
  • 87
  • 1
  • 2
  • 10

1 Answers1

6

you need a loop and read with a smaller buffer (like 1024 bytes) from the stream.

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

This should work for you

Tim
  • 6,692
  • 2
  • 25
  • 30