如何用java获取网络文件的大小
邰嘉骏
2023-06-13 20:41:27
共 1 个回答
黄洁雯
2023-06-17 16:26:27
import java.net.*;
import java.io.*;
public class URLConnectionDemo{
public static void main(String[] args)throws Exception{
URL url = new URL("
);
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);
}
}
阅读原文