Java URL Download downloadFile(String fileURL, String targetDirectory)

Here you can find the source of downloadFile(String fileURL, String targetDirectory)

Description

download File

License

Apache License

Declaration

public static File downloadFile(String fileURL, String targetDirectory) throws Exception 

Method Source Code


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

import java.io.BufferedInputStream;

import java.io.File;
import java.io.FileOutputStream;

import java.io.InputStream;

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

public class Main {
    public static File downloadFile(String fileURL, String targetDirectory) throws Exception {

        System.out.println("Retrieving: " + fileURL);

        String cacheDir = System.getProperty("cacheDirectory");
        if (cacheDir == null) {
            cacheDir = System.getProperty("java.io.tmpdir") + File.separator + "pdt-test-cache";
        }/*from  w  ww .  ja  va2  s  .  c  o m*/
        new File(cacheDir).mkdirs();

        URL url = new URL(fileURL);
        String fileName = url.getFile().substring(url.getPath().lastIndexOf('/') + 1);

        File cachedFile = new File(cacheDir, fileName);
        if (!cachedFile.exists()) {

            URLConnection urlConnection = url.openConnection();
            InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
            FileOutputStream outputStream = new FileOutputStream(cachedFile);
            byte[] bytes = new byte[8192];
            int count = inputStream.read(bytes);
            while (count != -1 && count <= bytes.length) {
                outputStream.write(bytes, 0, count);
                count = inputStream.read(bytes);
            }
            if (count != -1) {
                outputStream.write(bytes, 0, count);
            }
            inputStream.close();
            outputStream.close();

        } else {
            System.out.println("File: " + cachedFile.getAbsolutePath() + " already exists");
        }

        return cachedFile;
    }
}

Related

  1. downloadFile(File target, String urlStr)
  2. downloadFile(final String url)
  3. downloadFile(String fileURL, String localFileName, String destinationDir)
  4. downloadFile(String fileURL, String saveDir)
  5. downloadFile(String fileURL, String savePath)
  6. downloadFile(String url)
  7. downloadFile(String url, File output)
  8. downloadFile(String url, String fileName)
  9. downloadFile(String url, String fileName)