java通过url下载文件

通过流的方式进行下载:
 
代码如下:

    /**
     * 通过url地址进行下载文件
     * @param url 网页地址
     * @param fileName 文件名,不包含文件路径需要自己配置
     */
    public static void downloadByUrl(String url,String fileName){
        BufferedInputStream inputStream=null;
        FileOutputStream fileOutputStream=null;
        try {
            URL path=new URL(url);
            inputStream=new BufferedInputStream(path.openStream());
            fileOutputStream=new FileOutputStream(fileName);
            byte[] bytes=new byte[1024];//1m
            int len=0;//为什么需要记录长度,便于在写入的时候确定长度
            while ((len=inputStream.read(bytes))!=-1){
                fileOutputStream.write(bytes,0,len);//将读取的文件进行写出
            }
            fileOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

本文作者:just1t

本文链接:https://www.cnblogs.com/just1t/p/17176684.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   just1t  阅读(2139)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起