利用Java从URL下载文件并保存到指定目录

1.pom.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>tcl.down.url</groupId>
    <artifactId>downurl</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
    <dependency>
        <groupId>net.sf.json-lib</groupId>
        <artifactId>json-lib</artifactId>
        <version>2.4</version>
        <classifier>jdk15</classifier>
    </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.5</version>
        </dependency>

        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>downurl.Iputil</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

2.实现代码的方法

package downurl;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownUrl {
    /**
     * @从制定URL下载文件并保存到指定目录
     * @param filePath 文件将要保存的目录
     * @param method 请求方法,包括POST和GET
     * @param url 请求的路径
     * @return
     */

    public static File saveUrlAs(String url,String filePath,String method){
        //System.out.println("fileName---->"+filePath);
        //创建不同的文件夹目录
        File file=new File(filePath);
        //判断文件夹是否存在
        if (!file.exists())
        {
            //如果文件夹不存在,则创建新的的文件夹
            file.mkdirs();
        }
        FileOutputStream fileOut = null;
        HttpURLConnection conn = null;
        InputStream inputStream = null;
        try
        {
            // 建立链接
            URL httpUrl=new URL(url);
            conn=(HttpURLConnection) httpUrl.openConnection();
            //以Post方式提交表单,默认get方式
            conn.setRequestMethod(method);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            // post方式不能使用缓存
            conn.setUseCaches(false);
            //连接指定的资源
            conn.connect();
            //获取网络输入流
            inputStream=conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            //判断文件的保存路径后面是否以/结尾
            if (!filePath.endsWith("/")) {
                filePath += "/";
            }
            //写入到文件(注意文件保存路径的后面一定要加上文件的名称)

            fileOut = new FileOutputStream(filePath+url.substring(url.lastIndexOf("/")+1,url.lastIndexOf("?")));
            BufferedOutputStream bos = new BufferedOutputStream(fileOut);

            byte[] buf = new byte[4096];
            int length = bis.read(buf);
            //保存文件
            while(length != -1)
            {
                bos.write(buf, 0, length);
                length = bis.read(buf);
            }
            bos.close();
            bis.close();
            conn.disconnect();
        } catch (Exception e)
        {
            e.printStackTrace();
            System.out.println("抛出异常!!");
        }

        return file;

    }
    /**
     * @param args
     */
    public static void main(String[] args)
    {
        String photoUrl = "http://datacenter1.oss-cn-hangzhou.dasd.com/logclean/huannet/da/date%3D2020-06-01/part-dasda-07477e29-b6da-40b5-8c09-af5c4067606f-c000.snappy.parquet?Expires=1594915200&OSSAccessKeyId=dsa&Signature=4qATSNRtaW4u3TQsjPb%2B73KzqkM%3D";   //文件URL地址
//        String fileName = photoUrl.substring(photoUrl.lastIndexOf("/"));     //为下载的文件命名
        String fileName = "/tupian";
        String filePath = "e:";      //保存目录
        File file = saveUrlAs(photoUrl, filePath + fileName,"GET");
    }
}

猜你喜欢

转载自blog.csdn.net/summer089089/article/details/107090367
今日推荐