根据URL下载文件

commons-io 包中已经封装好了,直接可以使用

一、添加依赖

    <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
       <version>1.3.2</version> </dependency>

二、使用

/**
     * 通过url下载文件
     * @param fileName 下载的后文件的名字
     * @param downloadUrl url一定要有http://
     * @param savePath 下载到哪个路径
     */
    public static boolean downloadFileFromUrl(String fileName,String downloadUrl,String savePath){

        boolean result=false;
        try {

            //先判断文件是否存在
            File file1=new File(savePath+fileName);
            if(file1.exists()){
                System.out.println("删除已存在的文件");
                file1.delete();
            }
            long begin=System.currentTimeMillis();
            URL url=new URL(downloadUrl);
            File file=new File(savePath+fileName);
            org.apache.commons.io.FileUtils.copyURLToFile(url,file);
            long end=System.currentTimeMillis();
            System.out.println("文件下载耗时:"+(end-begin)/1000 +"s");
            //执行到此,说明文件下载完毕
            result=true;
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

  

原文地址:https://www.cnblogs.com/geekdc/p/9295442.html