Java URL Download downloadUrlToFile(String surl, File file, String method)

Here you can find the source of downloadUrlToFile(String surl, File file, String method)

Description

download Url To File

License

Open Source License

Declaration

public static void downloadUrlToFile(String surl, File file, String method) throws Exception 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

public class Main {
    public static void downloadUrlToFile(String surl, File file, String method) throws Exception {
        URL url = new URL(surl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        if (notEmpty(method))
            conn.setRequestMethod(method);
        else/*  w  w  w. jav  a 2  s  .  c  o  m*/
            conn.setRequestMethod("GET");
        conn.setDoInput(true);
        //
        conn.connect();
        if (!file.exists())
            file.createNewFile();

        FileOutputStream fos = new FileOutputStream(file);
        InputStream is = conn.getInputStream();
        byte[] buffer = new byte[1024 * 10];
        int read = is.read(buffer);

        int count = 0;
        while (read != -1) {
            count += read;
            byte[] dd = new byte[read];
            System.arraycopy(buffer, 0, dd, 0, read);
            fos.write(dd);
            read = is.read(buffer);
        }
        fos.close();
        conn.disconnect();
    }

    public static boolean notEmpty(String s) {
        return s != null && s.length() > 0;
    }

    public static boolean notEmpty(List s) {
        return s != null && s.size() > 0;
    }
}

Related

  1. downloadToString(String url)
  2. downloadURL(String addr, File outFile)
  3. downloadURL(String url, String outFile)
  4. downloadURL(URL url, File file)
  5. downloadURL(URL url, String localPath)
  6. downloadUrlToFile(URL url, File file)
  7. downloadUrlToFile(URL url, File result)
  8. downloadWebpage(String url)
  9. downloadZip(URL file, File dump)