集册 Java实例教程 将Url下载到文件

将Url下载到文件

欢马劈雪     最近更新时间:2020-01-02 10:19:05

474
下载网址到文件


import java.io.File;/* 来自 n o w j a v a . c o m - 时代Java*/

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;


public class Main{

    public static void downloadUrlToFile(String fromUrl, File to,

            ProgressListener progressListener) throws IOException {

        if (fromUrl == null || fromUrl.trim().isEmpty()) {

            throw new IllegalArgumentException("FromUrl is empty");

        }

        if (to == null) {/* 来自 时代Java公众号 - N o w J a  v a . c o m*/

            throw new IllegalArgumentException("Download to is empty");

        }


        URL url = new URL(fromUrl);

        HttpURLConnection connect = (HttpURLConnection) url

                .openConnection();

        connect.setRequestMethod("GET");

        connect.setDoOutput(true);

        connect.connect();


        FileOutputStream toStream = new FileOutputStream(to);

        InputStream fromStream = connect.getInputStream();


        if (fromStream == null) {

            return;

        }


        byte[] buffer = new byte[1024];

        int lenght = 0;

        int size = connect.getContentLength();

        int current = 0;


        while ((lenght = fromStream.read(buffer)) > 0) {

            toStream.write(buffer, 0, lenght);

            current += lenght;

         
展开阅读全文