在java中没有收到的字节数

时间:2011-11-07 17:18:11

标签: java http

我想确定从以下工作URL连接下载的字节数: 我有以下代码来实现:

   .......
   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");

最后一行的输出如下:

   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

我的代码有什么错误。请帮帮我

2 个答案:

答案 0 :(得分: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");

答案 1 :(得分:0)

int totalBytes = 0;
...
while((read = dis.read(bytes)) != -1)
{
    totalBytes += read;
    fos.write(bytes, 0, read);
}