Here you can find the source of downloadFile(String fileName, String url)
Parameter | Description |
---|---|
fileName | Name under which the file will be saved locally |
url | URL of hte file |
Parameter | Description |
---|---|
IOException | if downloading fails |
public static File downloadFile(String fileName, String url) throws IOException
//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); } }