Java URL Download downloadFileToGivenNameElseExtension( URLConnection urlConnection, String fileName)

Here you can find the source of downloadFileToGivenNameElseExtension( URLConnection urlConnection, String fileName)

Description

Downloads the file using the given URLConnection and saves it to a temp directory as a file with a supplied name unless it does not have permission to do so, in which case it saves it to the temp directory with whatever name it pleases, but with the extension of the supplied name.

License

Open Source License

Parameter

Parameter Description
fileName the base name (minus path) for the temp file that we hope to be able to rename to.

Return

the full path of the temp file

Declaration

public static String downloadFileToGivenNameElseExtension(
        URLConnection urlConnection, String fileName)
        throws IOException 

Method Source Code

//package com.java2s;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;

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

import java.net.URLConnection;

public class Main {
    private static final boolean DEBUG = false;

    /**//from   w w  w  .  j ava 2  s  .  c  o m
     * Downloads the file using the given {@link URLConnection} and saves it to a
     * temp directory as a file with a supplied name unless it does not have
     * permission to do so, in which case it saves it to the temp directory
     * with whatever name it pleases, but with the extension of the supplied
     * name.
     *
     * @param fileName the base name (minus path) for the temp file that we hope
     *    to be able to rename to.
     * @return the full path of the temp file
     */
    public static String downloadFileToGivenNameElseExtension(
            URLConnection urlConnection, String fileName)
            throws IOException {
        return createTempFile(
                new BufferedInputStream(urlConnection.getInputStream()),
                fileName);
    }

    private static String createTempFile(InputStream inputStream,
            String preferredName) throws IOException {
        String extension = "." + parseFileExtension(preferredName);
        // start by creating a temp file containing the contents of inputStream
        // and a name of File's choosing.
        File tempFile = File.createTempFile("aia", extension);
        OutputStream outputStream = new BufferedOutputStream(
                new FileOutputStream(tempFile));
        copy(inputStream, outputStream);
        inputStream.close();
        outputStream.flush();
        outputStream.close();
        tempFile.deleteOnExit();
        // try to renamed to preferredName
        File tempFileDirectory = tempFile.getParentFile();
        boolean success = true; // assume the best
        if (preferredName.indexOf('/') != -1) {
            // may need to create subdirectories
            int basenameStart = preferredName.lastIndexOf('/') + 1;
            File newDirs = new File(tempFileDirectory,
                    preferredName.substring(0, basenameStart));
            if (!newDirs.exists()) {
                success = newDirs.mkdirs();
            }
        }
        File renamedTempFile = new File(tempFileDirectory, preferredName);
        ;
        if (success) { // still good so far. try the rename
            success = tempFile.renameTo(renamedTempFile);
        }
        if (!success) {
            // We don't have permission to rename, so just fall back on tempFile name.
            if (DEBUG) {
                System.out.println("Attempt to rename "
                        + tempFile.getPath() + " to "
                        + renamedTempFile.getPath() + " failed");
            }
            return tempFile.getAbsolutePath();
        } else {
            return renamedTempFile.getAbsolutePath();
        }
    }

    private static String parseFileExtension(String path) {
        String extension = "";
        int dotPos = path.lastIndexOf('.');
        if (dotPos >= 0) {
            extension = path.substring(dotPos + 1);
        }
        return extension;
    }

    /**
     * Copies all bytes from the input stream to the output stream.
     * Does not close or flush either stream.
     *
     * @param from the InputStream to read from
     * @param to the OutputStream to write to
     * @return the number of bytes copied
     */
    private static long copy(InputStream from, OutputStream to)
            throws IOException {
        final int BUF_SIZE = 0x1000; // 4K
        byte[] buf = new byte[BUF_SIZE];
        long total = 0;
        while (true) {
            int r = from.read(buf);
            if (r == -1) {
                break;
            }
            to.write(buf, 0, r);
            total += r;
        }
        return total;
    }
}

Related

  1. downloadFileFromInternet(String remoteUrl)
  2. downloadFileFromUrl(String urlPath, File file)
  3. downloadFileFromWeb(URL resourceURL, String fullPath)
  4. downloadFileFromWebserver(String fileUrl, String storageLocation)
  5. downloadFileIfAvailable(URL url, File destination)
  6. downloadFromURL(String url)
  7. downloadFromUrl(String urlString, PrintStream logger)
  8. downloadFromUrl(URL url, String localFilename)
  9. downloadGzipCompressedFile(URL url, File destination)