2016-11-16 54 views
1

我从URL下载PDF并将其保存到本地驱动器。如何测量从URL下载的PDF的大小

下载代码工作正常,问题是当我尝试测量文件的大小时,它始终声称它是52字节。我很困惑...你能检查一下我的代码,告诉我我是否错过了一些东西?

try { 
       link = new URL("http://www.annualreports.co.uk/HostedData/AnnualReports/PDF/LSE_" + entry[0] + "_2015.pdf"); 
       // http://www.annualreports.co.uk/HostedData/AnnualReports/PDF/LSE_BT_2015.pdf 

       InputStream in = new BufferedInputStream(link.openStream()); 
       ByteArrayOutputStream out = new ByteArrayOutputStream(); 

       byte[] buf = new byte[1024]; 
       int n = 0; 
       while (-1!=(n=in.read(buf))) 
       { 
        out.write(buf, 0, n); 
       } 
       out.close(); 
       in.close(); 
       byte[] response = out.toByteArray(); 

       FileOutputStream fos = new FileOutputStream(fileName); 
       fos.write(response); 
       fos.close(); 

      } catch (Exception e) { 
       System.out.println("Couldn't retrieve : " + entry[1] + " " + year); 
      } 

      int bytes = fileName.length(); 
      System.out.println(bytes); 
+4

您似乎在测量'fileName'的长度,这可能是文件的名称。 – BadZen

+0

您正在打印文件**名称**的长度。咄! –

+0

啊对不起,这是多派。我是新来的!对业余爱好者的问题表示歉意......所以这段代码中是否有任何可以测量文件而不是文件名的对象? – will

回答

0

这里。只需简单地尝试一下。

URL url = new URL("http://www.annualreports.co.uk/HostedData/AnnualReports/PDF/LSE_" + entry[0] + "_2015.pdf"); 
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
conn.addRequestProperty("User-Agent", "Mozilla/4.76"); 
int size = conn.getContentLength(); 

     if (size < 0) { 
      System.out.println("File not found"); 
     } else { 
      System.out.println("File size in Bytes: " + size); 
     } 
+1

英雄,非常感谢! – will

+0

很高兴为你效劳。那么,你可以接受答案。 :) – m4heshd