Here you can find the source of downloadToFile(URL url, File file)
Parameter | Description |
---|---|
url | a parameter |
file | a parameter |
public static void downloadToFile(URL url, File file) throws IOException
//package com.java2s; /*//from w w w .j a v a 2s.c om * Copyright (C) 2017 CenturyLink, Inc. * * 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.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; public class Main { /** * Download a file from a URL. * * @param url * @param file */ public static void downloadToFile(URL url, File file) throws IOException { InputStream is = null; OutputStream os = null; try { URLConnection conn = url.openConnection(); conn.setUseCaches(false); byte[] buffer = new byte[2048]; is = conn.getInputStream(); os = new FileOutputStream(file); while (true) { int bytesRead = is.read(buffer); if (bytesRead == -1) break; os.write(buffer, 0, bytesRead); } } finally { if (is != null) is.close(); if (os != null) os.close(); } } }