Android URL Download downloadFile(URL url, OutputStream output)

Here you can find the source of downloadFile(URL url, OutputStream output)

Description

download File

License

Open Source License

Declaration

public static void downloadFile(URL url, OutputStream output)
            throws IOException 

Method Source Code

//package com.java2s;
/*/*from   ww  w .j a  va2  s .  co m*/
 * This file is part of ZSE Info.
 *
 *     ZSE Info is free software; you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation; either version 3 of the License, or
 *     any later version.
 *
 *     ZSE Info 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 General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with Foobar; if not, write to the Free Software
 *     Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    public static void downloadFile(URL url, OutputStream output)
            throws IOException {
        InputStream input = null;
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                throw new IOException("B??d po??czenia z serwerem: "
                        + connection.getResponseCode() + " "
                        + connection.getResponseMessage());
            }

            int fileLength = connection.getContentLength();

            input = connection.getInputStream();

            byte[] data = new byte[4096];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {

                total += count;

                output.write(data, 0, count);
            }
        } finally {
            try {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            } catch (IOException ignore) {
            }
            if (connection != null)
                connection.disconnect();
        }
    }
}

Related

  1. download(String url, String directoryName, String fileName)
  2. downloadFile(String downloadUrl, String outputFilePath)
  3. downloadHtmlPage(String pageUrl)
  4. downloadUrl(String urlString)
  5. getJSONResponseFromURL(String url, Hashtable httpGetParams)
  6. downloadJson(URI uri)