我们在URLConnection下载文件时使用吗?

时间:2015-10-25 13:22:21

标签: java image download

这是我的代码下载图片宽度百分比[Java]:

URL url = new URL(imageUrl);
    OutputStream os;
    URLConnection connection = url.openConnection();
    connection.connect();
    int fileLenth = connection.getContentLength();
    try (InputStream is = url.openStream()) {
        os = new FileOutputStream(destinationFile);
        byte[] b = new byte[2048];
        int length;
        int count = 0;
        double sumCount = 0.0;
        while ((length = is.read(b)) != -1) {
            os.write(b, 0, length);

            sumCount += count;
            if (fileLenth > 0) {
                System.out.println("Percentace: " + (sumCount / fileLenth * 100.0) + "%");
            }
        }
    }
    os.close();

我想知道我何时使用:

URLConnection connection = url.openConnection();
connection.connect();
int fileLenth = connection.getContentLength();

文件是否已下载? 如果是这样,该文件将被两次下载,这并不好 你能帮助我获得最佳表现吗? 感谢

1 个答案:

答案 0 :(得分:3)

getContentLength()方法无法下载文件,只返回content-length标题的值(如果有),more details here