要根据URL获取文件大小,你可以使用以下代码:

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileSizeFetcher {

    public static void main(String[] args) {
        String url = "https://example.com/file.txt"; // 替换为你要获取大小的文件的URL
        try {
            long fileSize = getFileSize(url);
            System.out.println("File size: " + fileSize + " bytes");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static long getFileSize(String fileUrl) throws IOException {
        URL url = new URL(fileUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("HEAD");
        conn.getInputStream();
        return conn.getContentLengthLong();
    }
}

在上面的代码中,getFileSize()方法使用HTTP HEAD请求来获取文件的大小。它打开URL连接,将请求方法设置为HEAD,然后获取输入流。最后,它返回连接的内容长度作为文件大小。

你需要将url变量替换为你要获取大小的文件的URL。然后,你可以调用getFileSize()方法来获取文件的大小。

android根据url获取文件大小

原文地址: https://www.cveoy.top/t/topic/i9lA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录