Java URL Download downloadFile(URL theURL, String filePath)

Here you can find the source of downloadFile(URL theURL, String filePath)

Description

download File

License

Apache License

Declaration

public static void downloadFile(URL theURL, String filePath) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Main {
    public static void downloadFile(URL theURL, String filePath) throws IOException {
        URLConnection con = theURL.openConnection();
        String urlPath = con.getURL().getFile();
        String fileFullName = urlPath.substring(urlPath.lastIndexOf("/") + 1);
        if (fileFullName != null) {
            byte[] buffer = new byte[4 * 1024];
            int read;
            String path = filePath + "/" + fileFullName;
            File fileFolder = new File(filePath);
            if (!fileFolder.exists()) {
                fileFolder.mkdir();// ww  w. ja va2  s .  c om
            }
            InputStream in = con.getInputStream();
            FileOutputStream os = new FileOutputStream(path);
            while ((read = in.read(buffer)) > 0) {
                os.write(buffer, 0, read);
            }
            os.close();
            in.close();
        }
    }

    public static void downloadFile(String urls, String filePath) {
        URL url;
        try {
            url = new URL(urls);
            try {
                downloadFile(url, filePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}

Related

  1. downloadFile(String urlPath, File file)
  2. downloadFile(String urlString)
  3. downloadFile(String urlString, String filename)
  4. downloadFile(String urlToDownload, File locationToStore)
  5. downloadFile(URL fileUrl, File out)
  6. downloadFile(URL url, File toFile)
  7. downloadFile(URL url, String name)
  8. downloadFile(URL url, String path, String fileName)
  9. downloadFileAndRetry(final File file, final URL url, final int retry)