📜  使用Java在 Internet 上的文件大小

📅  最后修改于: 2022-05-13 01:55:26.115000             🧑  作者: Mango

使用Java在 Internet 上的文件大小

要首先从服务器获取文件的大小,您需要使用URLHttpURLConnection类连接到服务器。要获取文件的大小,我们使用getContentLength()方法。由于文件的大小可能太大,我们使用BigInteger类。您不能使用整数数据类型,因为如果文件大小大于 2Gb,它会生成错误。
要了解有关BigInteger 类的更多信息,请参阅链接: Java中的 BigInteger 类
对于HttpURLConnection参考链接: Java.net.HttpURLConnection Class in Java

Java
// Java Program to calculate Size
// of a file on the Internet.
import java.math.BigInteger;
import java.net.URL;
import java.net.HttpURLConnection;
  
public class SizeFile {
      
    public static void main(String args[]) throws Exception
    {
        BigInteger size = new BigInteger("1");
  
        // get the url of web page
        URL url = new URL(
            "https://media.geeksforgeeks.org/wp-content/uploads/GATE.pdf");
      
        // create a connection
        HttpURLConnection conn;
        try
        {
                  
            // open stream to get size of page
            conn = (HttpURLConnection)url.openConnection();
              
            // set request method.
            conn.setRequestMethod("HEAD");
              
            // get the input stream of process
            conn.getInputStream();
              
            // store size of file
            size = BigInteger.valueOf(conn.getContentLength());
              
            // print the size of downloaded file
            System.out.println("The Size of file is:" +
                                       size + " bytes");
            conn.getInputStream().close();
        }
        catch (Exception e)
        {
            System.out.println("Connection failed");
        }
    }
}