获取网络URL文件的大小&网络图片的大小和后缀

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class TestSuit {
    public static void main(String[] args) {
        String mp3 = "ftp://static-bot.nearme.com.cn/1573713806068-postman.jpg";
        try{
            Map<String, Object> urlFileInfo = getUrlFileInfo(mp3);
            System.out.println(urlFileInfo.get("size"));
            System.out.println(urlFileInfo.get("imageWidth"));
            System.out.println(urlFileInfo.get("imageHeight"));
            System.out.println(urlFileInfo.get("fileSuffix"));
            System.out.println(urlFileInfo.get("fileName"));
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public static Map<String,Object> getUrlFileInfo(String urlPath) throws Exception{
        if(urlPath == null || urlPath.trim().length() == 0){
            return null;
        }
        Map<String,Object> info = new HashMap<String,Object>(16);
        try {
            // first Exception
            URL url = new URL(urlPath);

            // second Exception --IOException
            BufferedImage imageRead = ImageIO.read(url);

            info.put("imageWidth",imageRead.getWidth());
            info.put("imageHeight",imageRead.getHeight());
            byte[] array = new byte[1024];
            // third Exception --IOException
            InputStream inputStream = url.openStream();
            int size = 0;
            int length = 0;
            // fourth Exception --IOException
            while ((length = inputStream.read(array)) != -1) {
                size += length;
            }
            info.put("size",size);
            int lastIndex =urlPath.lastIndexOf(".");
            if(lastIndex < urlPath.length() - 1){
                info.put("fileSuffix",urlPath.substring(lastIndex+1));
            }
            String fileString = url.getFile();
            if(fileString.length()>0){
                info.put("fileName",fileString.substring(0,fileString.lastIndexOf(".")));
            }
            return info;
        } catch (MalformedURLException e) {
            throw new Exception("url缺少通信协议,请检查url是否正确");
        } catch (IOException e) {
            throw new Exception("网络位置的文件不存在,请检查url是否正确");
        }
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值