Java tutorial
//package com.java2s; import android.util.Log; import java.io.BufferedInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; public class Main { private static final String TAG = "NWhelper"; /** * Downloads a file via HTTP(S) GET to the given path. This function cannot be called from the * UI thread. Android does not allow it. * @param urlString Url to the ressource to download. * @param path path where the file should be saved. * @param overwrite if file exists, overwrite? * @return flase if download was not successful. If successful, true. */ private static Boolean fileDownloadHttp(String urlString, String path, Boolean overwrite) { return fileDownloadHttp(urlString, new File(path), overwrite); } /** * Downloads a file via HTTP(S) GET to the given path. This function cannot be called from the * UI thread. Android does not allow it. * * @param urlString Url to the ressource to download. * @param file file to be written to. * @param overwrite if file exists, overwrite? * @return flase if download was not successful. If successful, true. */ private static Boolean fileDownloadHttp(String urlString, File file, Boolean overwrite) { HashMap<String, String> result = null; URL url = null; // File temp; try { url = new URL(urlString); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setReadTimeout(200000); urlConnection.connect(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); FileOutputStream outputStream = new FileOutputStream(file); int read = 0; byte[] bytes = new byte[1024]; while ((read = in.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } in.close(); outputStream.close(); urlConnection.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } Log.d(TAG, "File download: " + file.getAbsolutePath() + url.getFile() + "overwrite " + overwrite + "exists? " + file.exists()); return true; } }