Java URL Download downloadToFile(URL url, File file)

Here you can find the source of downloadToFile(URL url, File file)

Description

Download a file from a URL.

License

Apache License

Parameter

Parameter Description
url a parameter
file a parameter

Declaration

public static void downloadToFile(URL url, File file) throws IOException 

Method Source Code

//package com.java2s;
/*//from  w  w  w  .j a v a 2s.c  om
 * Copyright (C) 2017 CenturyLink, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import java.net.URL;
import java.net.URLConnection;

public class Main {
    /**
     * Download a file from a URL.
     * 
     * @param url
     * @param file
     */
    public static void downloadToFile(URL url, File file) throws IOException {
        InputStream is = null;
        OutputStream os = null;
        try {
            URLConnection conn = url.openConnection();
            conn.setUseCaches(false);
            byte[] buffer = new byte[2048];
            is = conn.getInputStream();
            os = new FileOutputStream(file);
            while (true) {
                int bytesRead = is.read(buffer);
                if (bytesRead == -1)
                    break;
                os.write(buffer, 0, bytesRead);
            }
        } finally {
            if (is != null)
                is.close();
            if (os != null)
                os.close();
        }
    }
}

Related

  1. downloadTo(String url, String filename)
  2. downloadToDirectory(URL url, String directoryName)
  3. downloadToFile(String url, File file)
  4. downloadToFile(URL source, File dest)
  5. downloadToFile(URL url, File downloadFile)
  6. downloadToLocalFile(File targetFile, URL requestedURL, Proxy proxy)
  7. downloadToString(String url)
  8. downloadURL(String addr, File outFile)
  9. downloadURL(String url, String outFile)