Java URL Download nio downloadFile(String fileName, String url)

Here you can find the source of downloadFile(String fileName, String url)

Description

Downloads file located at given url and saves it with given filename in the current directory.

License

Open Source License

Parameter

Parameter Description
fileName Name under which the file will be saved locally
url URL of hte file

Exception

Parameter Description
IOException if downloading fails

Return

File which was downloaded

Declaration

public static File downloadFile(String fileName, String url)
        throws IOException 

Method Source Code

//package com.java2s;
/*//  w  ww  .j a v a2  s .  c  om
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

public class Main {
    /**
     * Downloads file located at given url and saves it with given filename in the current directory.
     *
     * @param fileName Name under which the file will be saved locally
     * @param url URL of hte file
     * @return File which was downloaded
     * @throws IOException if downloading fails
     */
    public static File downloadFile(String fileName, String url)
            throws IOException {
        final URL resourcesURL = new URL(url);
        final ReadableByteChannel rbc = Channels.newChannel(resourcesURL
                .openStream());
        FileOutputStream fos = new FileOutputStream(fileName);
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        fos.close();
        return new File(fileName);
    }
}

Related

  1. download(URL url, File out)
  2. download(URL url, Path location)
  3. download(URL url, String save)
  4. downloadAsync(String url, File file)
  5. downloadFile(final String url, final String downloadPath)
  6. downloadFile(String fileURL, String folderPath)
  7. downloadFile(String inputUrl, String destination)
  8. downloadFile(String sourceUrl, File destinationFile)
  9. downloadFile(String url, File output)