【问题标题】:How to measure the size of a PDF downloaded from a URL如何测量从 URL 下载的 PDF 的大小
【发布时间】:2016-11-16 20:02:52
【问题描述】:

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

【问题讨论】:

  • 你好像在测量fileName的长度,大概是文件名。
  • 您正在打印文件 name 的长度。呵呵!
  • 对不起,伙计们,那是愚蠢的。我是新来的!为业余问题道歉......那么这段代码中是否有任何对象可以测量文件而不是文件名?

标签: java filesize


【解决方案1】:

这里。试试这个吧。

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

【讨论】:

  • 很高兴它对你有用。好吧,那你就可以接受答案了。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-14
  • 1970-01-01
  • 2014-11-14
  • 2021-12-20
  • 2019-09-21
  • 2021-01-09
  • 1970-01-01
相关资源
最近更新 更多