Java tutorial
//package com.java2s; import java.io.BufferedInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import android.util.Log; public class Main { private static final String TAG = "HebrewBooksUtils"; public static File getFileFromCacheOrURL(File cacheDir, URL url) throws IOException { Log.i(TAG, "getFileFromCacheOrURL(): url = " + url.toExternalForm()); String filename = url.getFile(); int lastSlashPos = filename.lastIndexOf('/'); String fileNameNoPath = new String(lastSlashPos == -1 ? filename : filename.substring(lastSlashPos + 1)); File file = new File(cacheDir, fileNameNoPath); if (file.exists()) { if (file.length() > 0) { Log.i(TAG, "File exists in cache as: " + file.getAbsolutePath()); return file; } else { Log.i(TAG, "Deleting zero length file " + file.getAbsolutePath()); file.delete(); } } Log.i(TAG, "File " + file.getAbsolutePath() + " does not exists."); URLConnection ucon = url.openConnection(); ucon.setReadTimeout(5000); ucon.setConnectTimeout(30000); InputStream is = ucon.getInputStream(); BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5); FileOutputStream outStream = new FileOutputStream(file); byte[] buff = new byte[5 * 1024]; // Read bytes (and store them) until there is nothing more to read(-1) int len; while ((len = inStream.read(buff)) != -1) { outStream.write(buff, 0, len); } // Clean up outStream.flush(); outStream.close(); inStream.close(); return file; } }