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();
                }
            }
        }
    }
posted @ 2023-03-03 19:02  just1t  阅读(2076)  评论(0编辑  收藏  举报