天天看点

根据文件下载链接地址获取文件的大小根据网络文件的下载链接地址,获取文件的大小

根据网络文件的下载链接地址,获取文件的大小

直接上代码(记住要关闭相关的流)

/** 
 * 根据地址获得数据的字节流并转换成大小 
 * @param strUrl 网络连接地址 
 * @return 
 */  
public static String getFileSizeByUrl(String strUrl){ 
    InputStream inStream=null;
    ByteArrayOutputStream outStream=null;
    String size="";
    try {  
        URL url = new URL(strUrl);  
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
        conn.setRequestMethod("GET");  
        conn.setConnectTimeout(5 * 1000);  
        inStream = conn.getInputStream();

        outStream = new ByteArrayOutputStream();  
        byte[] buffer = new byte[1024];  
        int len = 0;  
        while( (len=inStream.read(buffer)) != -1 ){  
            outStream.write(buffer, 0, len);  
        }
        byte[] bt =  outStream.toByteArray();

        if(null != bt && bt.length > 0){
            DecimalFormat df = new DecimalFormat("#.00");
            if (bt.length < 1024) {
                size = df.format((double) bt.length) + "BT";
            } else if (bt.length < 1048576) {
                size = df.format((double) bt.length / 1024) + "KB";
            } else if (bt.length < 1073741824) {
                size = df.format((double) bt.length / 1048576) + "MB";
            } else {
                size = df.format((double) bt.length / 1073741824) +"GB";
            }
            System.out.println("文件大小=:" + size);  
        }else{  
            System.out.println("没有从该连接获得内容");  
        }
        inStream.close();
        outStream.close();
    } catch (Exception e) {  
        e.printStackTrace();  
    }finally{
        try{
            if(inStream !=null){
                inStream.close();
            }
            if(outStream !=null){
                outStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } 
    return size;  
}  
           

继续阅读