Android examples for Network:URL
download File from URL
//package com.java2s; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; public class Main { private static final int BUFFER_SIZE = 1024 * 4; public static boolean downloadFile(File file, URL url) throws IOException { BufferedInputStream bis = null; BufferedOutputStream bos = null; HttpURLConnection conn = null; try {// w ww . ja va2s . co m conn = (HttpURLConnection) url.openConnection(); bis = new BufferedInputStream(conn.getInputStream()); bos = new BufferedOutputStream(new FileOutputStream(file)); int contentLength = conn.getContentLength(); byte[] buffer = new byte[BUFFER_SIZE]; int read = 0; int count = 0; while ((read = bis.read(buffer)) != -1) { bos.write(buffer, 0, read); count += read; } if (count < contentLength) return false; int responseCode = conn.getResponseCode(); if (responseCode / 100 != 2) { // error return false; } // finished return true; } finally { try { bis.close(); bos.close(); conn.disconnect(); } catch (Exception e) { } } } }