Java如何從伺服器獲取檔案大小?

2019-10-16 22:27:59

在Java程式設計中,如何從伺服器獲取檔案大小?

以下範例演示如何從伺服器獲取檔案大小。

package com.yiibai;

import java.net.URL;
import java.net.URLConnection;

public class GettingFileSize {
    public static void main(String[] argv) throws Exception {
        int size;
        URL url = new URL("https://www.tw511.com/downloads/host.txt");
        URLConnection conn = url.openConnection();
        size = conn.getContentLength();

        if (size < 0)
            System.out.println("Could not determine file size.");
        else
            System.out.println("The size of file is = " + size + " bytes");
        conn.getInputStream().close();
    }
}

上述程式碼範例將產生以下結果 -

The size of file is = 180822 bytes

範例-2

以下是如何從伺服器獲取檔案大小的另一個範例。

package com.yiibai;

import java.net.URL;
import java.net.URLConnection;

public class GettingFileSize2 {
    public static void main(String[] argv) throws Exception {
        int size;
        URL url = new URL("/upload/images/yiibaidb.zip");
        URLConnection conn = url.openConnection();
        size = conn.getContentLength();
        if (size < 0)
            System.out.println("file size is empty.");
        else
            System.out.println("File size is = " + size + " bytes");
        conn.getInputStream().close();
    }
}

上述程式碼範例將產生以下結果 -

File size is = 60098 bytes