Android下儲存簡單網頁到本地(包括簡單圖片連結轉換)實現程式碼

Android下儲存簡單網頁到本地(包括簡單圖片連結轉換)實現程式碼

最近在做一個專案涉及到將包含圖片的簡單網頁下載到本地,方便離線時觀看,在這裡分享一下,大家做下簡單修改就可以用到自己的專案中了。(這裡用到了AQuery庫)

複製程式碼 程式碼如下:
package com.nekocode.xuedao.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.nekocode.xuedao.PublicData;
import com.nekocode.xuedao.PublicData.Subscribe;

public class HtmlStorageHelper {
 private String URL = “http://eduproject.sinaapp.com/fetchurl.php/getcontent/”;
 private PublicData pd;
 private AQuery aq;
 private SQLiteDatabase mDB;
 private String mDownloadPath;

 public HtmlStorageHelper(Context context) {
  pd = PublicData.getInstance();
  aq = new AQuery(context);
  mDB = context.openOrCreateDatabase(“data.db”, Context.MODE_PRIVATE, null);
  mDB.execSQL(“create table if not exists download_html(_id INTEGER PRIMARY KEY AUTOINCREMENT, content_id TEXT NOT NULL, title TEXT NOT NULL)”);

  mDownloadPath = pd.mAppPath “download/”;
  File dir_file = new File(pd.mAppPath “download/”);
  if(!dir_file.exists())
   dir_file.mkdir();
 }

 public void saveHtml(final String id, final String title) {
  if(isHtmlSaved(id))
   return;

  aq.ajax(URL id, String.class, new AjaxCallback<String>() {
   @Override
   public void callback(String url, String html, AjaxStatus status) {
    File dir_file = new File(mDownloadPath id);
    if(!dir_file.exists())
     dir_file.mkdir();

    Pattern pattern = Pattern.compile(“(?<=src=\”)[^\”] (?=\”)”);
    Matcher matcher = pattern.matcher(html);
    StringBuffer sb = new StringBuffer();
    while(matcher.find()){
     downloadPic(id, matcher.group(0));
     matcher.appendReplacement(sb, formatPath(matcher.group(0)));
    }
    matcher.appendTail(sb);
    html = sb.toString();

    writeHtml(id, title, html);
   }
  });
 }

 private void downloadPic(String id, String url) {
  File pic_file = new File(mDownloadPath id “/” formatPath(url));
  aq.download(url, pic_file, new AjaxCallback<File>() {
   @Override
   public void callback(String url, final File file, AjaxStatus status) {
   }
  });
 }

 private void writeHtml(String id, String title, String html) {
  File html_file = new File(mDownloadPath id “/index.html”);
  FileOutputStream fos = null;
  try {
   fos=new FileOutputStream(html_file);
            fos.write(html.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                fos.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

  ContentValues values = new ContentValues();
  values.put(“content_id”, id);
  values.put(“title”, title);
  mDB.insert(“download_html”, “_id”, values);
 }

 public boolean isHtmlSaved(String id) {
  File file = new File(mDownloadPath id);
  if(file.exists()) {
   file = new File(mDownloadPath id “/index.html”);
   if(file.exists())
    return true;
  }
  deleteHtml(id);
  return false;
 }

 public String getTitle(String id) {
  Cursor c = mDB.rawQuery(“select * from download_html where content_id=?”, new String[]{id});
  if(c.getCount() == 0)
   return null;

  c.moveToFirst();
  int index1 = c.getColumnIndex(“title”);

  return c.getString(index1);
 }

 public ArrayList<Subscribe> getHtmlList() {
  Cursor c = mDB.rawQuery(“select * from download_html”, null);
  ArrayList<Subscribe> list = new ArrayList<Subscribe>();
  if(c.getCount() != 0) {
   c.moveToFirst();
   int index1 = c.getColumnIndex(“content_id”);
   int index2 = c.getColumnIndex(“title”);

   while (!c.isAfterLast()) {
    String id = c.getString(index1);
    if(isHtmlSaved(id)) {
     Subscribe sub = new Subscribe(
       id,
       c.getString(index2),
       Subscribe.FILE_DOWNLOADED
       );
     list.add(sub);
    }

    c.moveToNext();
   }
  }

  return list;
 }

 public void deleteHtml(String id) {
  mDB.delete(“download_html”, “content_id=?”, new String[]{id});
  File dir_file = new File(mDownloadPath id);
  deleteFile(dir_file);
 }

 private void deleteFile(File file) {
  if (file.exists()) { // 判斷檔案是否存在
   if (file.isFile()) { // 判斷是否是檔案
    file.delete(); // delete()方法 你應該知道 是刪除的意思;
   } else if (file.isDirectory()) { // 否則如果它是一個目錄
    File files[] = file.listFiles(); // 宣告目錄下所有的檔案 files[];
    for (int i = 0; i < files.length; i ) { // 遍歷目錄下所有的檔案
     this.deleteFile(files[i]); // 把每個檔案 用這個方法進行迭代
    }
   }
   file.delete();
  } else {
   //
  }
 }

 private String formatPath(String path) {
        if (path != null && path.length() > 0) {
            path = path.replace(“\\”, “_”);
            path = path.replace(“/”, “_”);
            path = path.replace(“:”, “_”);
            path = path.replace(“*”, “_”);
            path = path.replace(“?”, “_”);
            path = path.replace(“\””, “_”);
            path = path.replace(“<“, “_”);
            path = path.replace(“|”, “_”);
            path = path.replace(“>”, “_”);
        }
        return path;
    }
}

您可能感興趣的文章:

Android實現點選WebView介面中圖片滑動瀏覽與儲存圖片功能Android實現儲存圖片到本地並在相簿中顯示基於Android實現儲存圖片到本地並可以在相簿中顯示出來android建立資料庫(SQLite)儲存圖片示例Android畫圖並儲存圖片的具體實現程式碼Android實現呼叫系統相簿與相機設定頭像並儲存在本地及伺服器Android程式設計實現呼叫系統相簿與裁剪圖片功能android從系統相簿中取圖片的例項程式碼android儲存Bitmap圖片到指定資料夾示例Android截圖儲存png圖片的例項程式碼Android實現從網路獲取圖片顯示並儲存到SD卡的方法Android程式設計實現儲存圖片到系統相簿的方法示例