Java URL Download download(String downloadUrlStr, String filename)

Here you can find the source of download(String downloadUrlStr, String filename)

Description

download data from url.

License

Open Source License

Parameter

Parameter Description
downloadUrlStr download url
filename save file name(not path, file name only).

Declaration

public static void download(String downloadUrlStr, String filename) throws Exception 

Method Source Code

//package com.java2s;
/**/*  ww w.j  ava2s . c o  m*/
 * API License
 */

import java.io.File;

import java.io.FileOutputStream;
import java.io.InputStream;

import java.net.URL;

public class Main {
    /**
     * download data from url.
     *
     * @param downloadUrlStr download url
     * @param filename       save file name(not path, file name only).
     */
    public static void download(String downloadUrlStr, String filename) throws Exception {
        File downloadDir = new File(new File(".", "download").getAbsolutePath());
        if (!downloadDir.exists()) {
            downloadDir.mkdirs();
        }
        File filepath = new File(downloadDir, filename);

        System.out.println("------------------------------------");
        System.out.println("Start download.");
        System.out.println("DOWNLOAD_URL  = " + downloadUrlStr);
        System.out.println("DOWNLOAD_FILE = " + filepath.getAbsolutePath());
        System.out.println("------------------------------------");

        InputStream is = null;
        FileOutputStream fos = null;
        try {
            URL downloadURL = new URL(downloadUrlStr);
            // get InputStream from download URL.
            is = downloadURL.openConnection().getInputStream();
            // create file output stream
            fos = new FileOutputStream(filepath, false);
            // download
            int b;
            while ((b = is.read()) != -1) {
                fos.write(b);
            }
        } finally {
            if (is != null) {
                is.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
    }
}

Related

  1. downImg(String filePath, String imageUrl, String fileName)
  2. download(final String sURL, final String sFilename)
  3. download(final URL url)
  4. download(String fileUrl, String savePath, String fileName)
  5. download(String url)
  6. download(String url, String path)
  7. download(String url, String saveFile)