URL url = new URL(urlString); File tempFile = null; tempFile = File.createTempFile("cache", ".tmp", new File(Environment.getExternalStorageDirectory().toString())); boolean downloaded = DownloadUtils.requestDownload(url, tempFile); public class DownloadUtils { private static final String TAG = "DownloadService"; public static boolean requestDownload(URL url, File file) { FileOutputStream fos = null; try { fos = new FileOutputStream(file); return download(url, fos); } catch (Throwable t) { return false; } finally { Utils.closeSilently(fos); } } public static void dump(InputStream is, OutputStream os) throws IOException { byte buffer[] = new byte[4096]; int rc = is.read(buffer, 0, buffer.length); final Thread thread = Thread.currentThread(); while (rc > 0) { os.write(buffer, 0, rc); rc = is.read(buffer, 0, buffer.length); } Thread.interrupted(); // consume the interrupt signal } public static boolean download(URL url, OutputStream output) { InputStream input = null; try { input = url.openStream(); dump(input, output); return true; } catch (Throwable t) { Log.w(TAG, "fail to download", t); return false; } finally { Utils.closeSilently(input); } } }
作者:zmyde2010 发表于2013-4-11 17:18:06 原文链接
阅读:0 评论:0 查看评论