有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

http没有在java中接收的字节数

我想确定从以下工作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) 个答案

  1. # 1 楼答案

       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");
    
  2. # 2 楼答案

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