Java URL Download downloadTo(String url, String filename)

Here you can find the source of downloadTo(String url, String filename)

Description

download To

License

Apache License

Declaration

public static long downloadTo(String url, String filename) 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.URL;

public class Main {
    /**//from   ww w .j  ava2 s. c om
     * The default buffer size to use.
     */
    private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;

    public static long downloadTo(String url, String filename) throws IOException {
        URL httpUrl = new URL(url);

        File file = new File(filename);
        file.deleteOnExit();

        if (file.exists()) {
            if (file.isDirectory()) {
                throw new IOException("File '" + file + "' exists but is a directory");
            }
            if (file.canWrite() == false) {
                throw new IOException("File '" + file + "' cannot be written to");
            }
        } else {
            File parent = file.getParentFile();
            if (parent != null && parent.exists() == false) {
                if (parent.mkdirs() == false) {
                    throw new IOException("File '" + file + "' could not be created");
                }
            }
        }

        FileOutputStream output = null;
        try {
            output = new FileOutputStream(file);
            InputStream input = httpUrl.openStream();

            try {
                byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
                long count = 0;
                int n = 0;
                while (-1 != (n = input.read(buffer))) {
                    output.write(buffer, 0, n);
                    count += n;
                }
                return count;
            } finally {
                if (input != null) {
                    input.close();
                }
            }
        } finally {
            if (output != null) {
                output.close();
            }
        }
    }
}

Related

  1. downloadString(String url)
  2. downloadString(URL url)
  3. downloadString(URL url)
  4. downloadText(String url)
  5. downloadTextFromUrl(String url)
  6. downloadToDirectory(URL url, String directoryName)
  7. downloadToFile(String url, File file)
  8. downloadToFile(URL source, File dest)
  9. downloadToFile(URL url, File downloadFile)