4.获取网络资源的大小,根据资源的url下载资源

1)核心代码

public static void main(String[] args) throws IOException {
    
    
    String urlStr=" https://cn.bing.com/sa/simg/Flag_Feedback.png";
    System.out.println(getResourceLength(urlStr));
    downResource(urlStr);
}

/**
 * 给定url地址获取资源的大小(以字节为单位)
 * @param urlStr
 * @return
 * @throws IOException
 */
public static long getResourceLength(String urlStr) throws IOException {
    
    
    URL url=new URL(urlStr);
    URLConnection urlConnection=url.openConnection();
    urlConnection.connect();
    return urlConnection.getContentLength();
}

/**
 * 下载指定url下的文件
 * @param urlStr url
 * @return
 */
public static void downResource(String urlStr){
    
    
    try{
    
    
        //创建URL对象
        URL url=new URL(urlStr);
        //获得链接对象
        URLConnection urlConnection=url.openConnection();
        //打开到url引用资源的通信链接
        urlConnection.connect();
        //获得输入流对象
        InputStream inputStream=urlConnection.getInputStream();
        //获得完整路径
        String filePath = url.getFile();
        int pos=filePath.lastIndexOf("/");
        //创建输出流对象
        FileOutputStream out=new FileOutputStream(filePath.substring(pos+1));
        byte[] bytes=new byte[1024];
        int len = inputStream.read(bytes);
        while(len!=-1){
    
    
            out.write(bytes,0,len);
            len=inputStream.read(bytes);
        }
        out.close();
        inputStream.close();
        System.out.println("下载完毕!!!");
    }catch (Exception e){
    
    
        e.printStackTrace();
    }
}

在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/c1776167012/article/details/120627071
今日推荐