1

I would like to determine the number of bytes downloaded from the following working URL connection: I have following code to implement:

   .......
   HttpURLConnection connection = (HttpURLConnection) url.openConnection();
   connection.connect();
   InputStream is = connection.getInputStream();   // throws an IOException
   DataInputStream dis = new DataInputStream(new BufferedInputStream(is));          

   FileOutputStream fos = new FileOutputStream("C:\\Picture.jpeg");
   int read =0;
   byte[] bytes = new byte[1024];
   while((read = dis.read(bytes)) != -1)
   {
        fos.write(bytes, 0, read);
   }
   System.out.println(read + " byte(s) copied");

The output from the last line is as follows:

   Opening connection to http://www.xyz.com//Picture.jpeg...
   Copying image resource (type: application/jpeg, modified on: 02/02/2010 4:19:21 AM)...
  -1 byte(s) copied

What is the error of my code. please help me

home
  • 12,169
  • 5
  • 42
  • 54
  • 3
    Don't get it. After the loop `read` will always be `-1`, otherwise you would have run into an infinite loop. What is the concrete problem? – home Nov 07 '11 at 17:22
  • Please follow the this link, which is same as your problem. http://stackoverflow.com/questions/6081796/menu-item-enable-disable Check out this links, Which is more helpful to solve your problem. http://www.eclipsezone.com/eclipse/forums/t90781.rhtml and http://www.odevelop.com/blog/?p=211 – Horrorgoogle Nov 07 '11 at 17:27

2 Answers2

3
   int read =0;
   int reddit = 0;
   byte[] bytes = new byte[1024];
   while((read = dis.read(bytes)) != -1)
   {
        fos.write(bytes, 0, read);
        reddit += read;
   }
   //your read variable must have the value -1 at this point
   System.out.println(reddit + " byte(s) copied");
bpgergo
  • 14,789
  • 2
  • 37
  • 60
0
int totalBytes = 0;
...
while((read = dis.read(bytes)) != -1)
{
    totalBytes += read;
    fos.write(bytes, 0, read);
}
Gabriel Negut
  • 12,932
  • 3
  • 34
  • 43