如何测量从 URL 下载的 PDF 文件的大小

How to measure the size of a PDF downloaded from a URL

我正在从 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);

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

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