Java URL Download downloadFile(String urlString, String filename)

Here you can find the source of downloadFile(String urlString, String filename)

Description

Download the url page content and save it to local file

License

Apache License

Parameter

Parameter Description
urlString a parameter
filename a parameter

Exception

Parameter Description
Exception an exception

Declaration

public static void downloadFile(String urlString, String filename) throws Exception 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2014 eBay Software Foundation.
 *
 * 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./*  w  ww  .ja v  a2 s .c o  m*/
 *******************************************************************************/

import java.io.FileOutputStream;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

public class Main {
    /**
     * Download the url page content and save it to local file
     * 
     * @param urlString
     * @param filename
     * @throws Exception
     */
    public static void downloadFile(String urlString, String filename) throws Exception {
        URL url = new URL(urlString);
        URLConnection con = url.openConnection();
        con.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko/20100101 Firefox/11.0");
        InputStream is = con.getInputStream();

        byte[] bs = new byte[1024];
        int len;
        OutputStream os = new FileOutputStream(filename);
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        os.close();
        is.close();
    }
}

Related

  1. downloadFile(String url, String fileName)
  2. downloadFile(String url, String filePath, File parent)
  3. downloadFile(String url, String path)
  4. downloadFile(String urlPath, File file)
  5. downloadFile(String urlString)
  6. downloadFile(String urlToDownload, File locationToStore)
  7. downloadFile(URL fileUrl, File out)
  8. downloadFile(URL theURL, String filePath)
  9. downloadFile(URL url, File toFile)