如何用java获取网络文件的大小

2025-03-01 20:07:51
推荐回答(4个)
回答1:

你好,这边有一个示例代码,希望对你有所帮助。示例中的urlString,你可以下载之后看看是否跟打印信息大小一致。我这边是一致的。

p:所导入的包都是java.net下面的。

main方法中 直接调用这个函数即可。 

static  int getNetWorkFile( ){
   String  urlString="https://img-blog.csdn.net/20180323154952670?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0p1c3RDbGltYmluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70";
    int length=0;
    URL url;
    try {
        url = new  URL(urlString);
        HttpURLConnection urlcon=(HttpURLConnection)url.openConnection();//打开连接
        //根据响应获取文件大小
        length=urlcon.getContentLength();
        urlcon.disconnect();//关闭连接
    } catch (Exception e) {    
        e.printStackTrace();
    }
    System.out.println(length);
    return length;
}

回答2:

在接受文件的时候可以根据不断获取TCP包中的BUFFER大小进行统计文件的大小

回答3:

不同的协议,有不同的方法,FTP 有命令可以取得。

回答4:

import java.net.*;
import java.io.*;
public class URLConnectionDemo{
    public static void main(String[] args)throws Exception{
        URL url = new URL("http://www.scp.edu.cn/pantoschoolzz/BG/Bord/Message/DownloadMessageAttachment.aspx?ID=215");
        URLConnection uc = url.openConnection();
        String fileName = uc.getHeaderField(6);
        fileName = URLDecoder.decode(fileName.substring(fileName.indexOf("filename=")+9),"UTF-8");
        System.out.println("文件名为:"+fileName);
        System.out.println("文件大小:"+(uc.getContentLength()/1024)+"KB");
        String path = "D:"+File.separator+fileName;
        FileOutputStream os = new FileOutputStream(path);
        InputStream is = uc.getInputStream();
        byte[] b = new byte[1024];
        int len = 0;
        while((len=is.read(b))!=-1){
            os.write(b,0,len);
        }
        os.close();
        is.close();
        System.out.println("下载成功,文件保存在:"+path);
    }
}