一个认真学习的网管 2021-10-13 18:08 采纳率: 0%
浏览 28

android ,根据网络图片或者视频地址,怎么获取到文件的大小呢? 百度上的方法试了,都报错,很无奈了,求大老解!


import android.icu.math.BigDecimal;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class TestUtils {

//    /**
//     * 根据图片地址获取图片信息
//     * @param urlPath   网络图片地址
//     * @return
//     */
//    public static byte[] getImageFromURL(String urlPath) {
//        // 字节数组
//        byte[] data = null;
//        // 输入流
//        InputStream is = null;
//        // Http连接对象
//        HttpURLConnection conn = null;
//        try {
//            // Url对象
//            URL url = new URL(urlPath);
//            // 打开连接
//            conn = (HttpURLConnection) url.openConnection();
//            // 打开读取 写入是setDoOutput
////            conn.setDoOutput(true);
//            conn.setDoInput(true);
//            // 设置请求方式
//            conn.setRequestMethod("GET");
//            // 设置超时时间
//            conn.setConnectTimeout(6000);
//            // 得到访问的数据流
//            is = conn.getInputStream();
//            // 验证访问状态是否是200 正常
//            if (conn.getResponseCode() == 200) {
//                data = readInputStream(is);
//            } else{
//                data=null;
//            }
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                if(is != null){
//                    // 关闭流
//                    is.close();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            // 关闭连接
//            conn.disconnect();
//        }
//        return data;
//    }
//
//    /**
//     * 将流转换为字节
//     * @param is
//     * @return
//     */
//    public static byte[] readInputStream(InputStream is) {
//        /**
//         * 捕获内存缓冲区的数据,转换成字节数组
//         * ByteArrayOutputStream类是在创建它的实例时,程序内部创建一个byte型别数组的缓冲区,然后利用ByteArrayOutputStream和ByteArrayInputStream的实例向数组中写入或读出byte型数据。
//         * 在网络传输中我们往往要传输很多变量,我们可以利用ByteArrayOutputStream把所有的变量收集到一起,然后一次性把数据发送出去。
//         */
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        // 创建字节数组 1024 = 1M
//        byte[] buffer = new byte[1024];
//        // 防止无限循环
//        int length = -1;
//        try {
//            // 循环写入数据到字节数组
//            while ((length = is.read(buffer)) != -1) {
//                baos.write(buffer, 0, length);
//            }
//            // 强制刷新,扫尾工作,主要是为了,让数据流在管道的传输工程中全部传输过去,防止丢失数据
//            baos.flush();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        // 字节流转换字节数组
//        byte[] data = baos.toByteArray();
//        try {
//            // 关闭读取流
//            is.close();
//            // 关闭写入流
//            baos.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return data;
//    }
//

    /**
     * @author Jayvee
     * @Description: todo 获取网络文件的大小
     */
    public static int getFileLength(String url1) throws IOException {
        int length = 0;
        URL url;
        try {
            url = new URL(url1);
            HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
            //根据响应获取文件大小
            length = urlcon.getContentLength();
            urlcon.disconnect();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return length;
    }


    /**
     * 根据图片地址获取图片信息
     *
     * @param urlPath 网络图片地址
     * @return
     */
    public static byte[] getImageFromURL(String urlPath) {
        byte[] data = null;
        InputStream is = null;
        HttpURLConnection conn = null;
        try {
            URL url = new URL(urlPath);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(6000);
            is = conn.getInputStream();
            if (conn.getResponseCode() == 200) {
                data = readInputStream(is);
            } else {
                data = null;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            conn.disconnect();
        }
        return data;
    }

    /**
     * 将流转换为字节
     *
     * @param is
     * @return
     */
    public static byte[] readInputStream(InputStream is) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length = -1;
        try {
            while ((length = is.read(buffer)) != -1) {
                baos.write(buffer, 0, length);
            }
            baos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] data = baos.toByteArray();
        try {
            is.close();
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }


    /**
     * //     * 获取本地图片的字节数
     * //     * @param imgPath
     * //     * @return
     * //
     */
    public static String pathSize(String imgPath) {
        File file = new File(imgPath);
        FileInputStream fis;
        int fileLen = 0;
        try {
            fis = new FileInputStream(file);
            fileLen = fis.available();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytes2kb(fileLen);
    }

    /**
     * 将获取到的字节数转换为KB,MB模式
     *
     * @param bytes
     * @return
     */
    public static String bytes2kb(long bytes) {
        BigDecimal filesize = new BigDecimal(bytes);
        BigDecimal megabyte = new BigDecimal(1024 * 1024);
        float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP).floatValue();
        if (returnValue > 1)
            return (returnValue + "MB");
        BigDecimal kilobyte = new BigDecimal(1024);
        returnValue = filesize.divide(kilobyte, 2, BigDecimal.ROUND_UP).floatValue();
        return (returnValue + "KB");
    }


//    /**
//     * 根据地址获得数据的字节流并转换成大小
//     * @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;
//    }
}

  
   ps: 这里是使用那个方法,但是报错了
  private void ceshi() {

        // 随便一个网络图片地址
//        String urlpath = "http://tx.csyuejia.cn//file/密码云相册/2021101315395770_30f0ba1130f32f4a.jpg";
//        // 得到数据
////        byte[] imageFromURL = TestUtils.getImageFromNetByUrl(urlpath);
//        // 转换
//        String byte2kb = TestUtils.bytes2kb(imageFromURL.length);
//        //输出
//        LogUtils.debugInfo("aaaa" + "图片的字节数:" + imageFromURL.length + "图片的大小:"+byte2kb);

    }
  • 写回答

2条回答 默认 最新

  • 关注

    请求head设置属性试试,

    setRequestProperty("Accept-Encoding", "identity");
    
    再调用如下方法获取:
    getContentLength();
    
    
    评论

报告相同问题?

问题事件

  • 创建了问题 10月13日

悬赏问题

  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了