Java URL Download nio downloadFile(URL url, File output)

Here you can find the source of downloadFile(URL url, File output)

Description

Download a file

License

Apache License

Parameter

Parameter Description
url The URL of the file to download
output The output File

Exception

Parameter Description
IOException If it failed downloading

Return

The download file (=output)

Declaration

public static File downloadFile(URL url, File output) throws IOException 

Method Source Code

//package com.java2s;
/*// w ww .j  a  v  a  2s . com
 * Copyright 2015 TheShark34
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

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

import java.io.IOException;

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

import java.nio.channels.Channels;

import java.nio.channels.ReadableByteChannel;

public class Main {
    /**
     * The size of the current downloading file
     */
    private static long downloadingFileSize;
    /**
     * The current downloading file
     */
    private static File downloadingFile;

    /**
     * Download a file
     * 
     * @param url
     *            The {@link URL} of the file to download
     * @param output
     *            The output {@link File}
     * @return The download file (=output)
     * @throws IOException
     *             If it failed downloading
     */
    public static File downloadFile(URL url, File output) throws IOException {
        output.getParentFile().mkdirs();
        downloadingFile = output;
        URLConnection connection = url.openConnection();
        downloadingFileSize = connection.getContentLengthLong();
        ReadableByteChannel rbc = Channels.newChannel(connection.getInputStream());
        FileOutputStream fos = new FileOutputStream(output);
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        fos.close();
        return output;
    }
}

Related

  1. downloadFile(String url, String localFilePath)
  2. downloadFile(String url, String location)
  3. downloadFile(String url, String location)
  4. downloadFile(String urlPath, String local)
  5. downloadFile(URL downloadUrl, File destination)
  6. downloadFile(URL url, File targetFile)
  7. downloadFileNIO(FileChannel fileChannel, SocketChannel socketChannel)
  8. downloadFileToDirectory(String url, File destination)
  9. downloadFirstLineFromInternetQuietly(URL url)