Here you can find the source of downloadFile(URL url, File output)
Parameter | Description |
---|---|
url | The URL of the file to download |
output | The output File |
Parameter | Description |
---|---|
IOException | If it failed downloading |
public static File downloadFile(URL url, File output) throws IOException
//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; } }