Android下保存简单网页到本地(包括简单图片链接转换)实现代码

时间:2021-05-27 03:45:52 

最近在做一个项目涉及到将包含图片的简单网页下载到本地,方便离线时观看,在这里分享一下,大家做下简单修改就可以用到自己的项目中了。(这里用到了AQuery库)

Android下保存简单网页到本地(包括简单图片链接转换)实现代码


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,网页,本地
0
投稿

猜你喜欢

  • C#验证身份证的函数

    2022-06-16 04:49:37
  • 解读JSONArray删除元素的两种方式

    2022-10-31 11:40:50
  • 如何在springboot中实现页面的国际化

    2021-08-13 03:33:07
  • 基于Fedora14下自带jdk1.6版本 安装jdk1.7不识别的解决方法

    2022-05-17 19:27:39
  • Android开发跳转应用市场进行版本更新功能实现

    2021-12-25 09:24:39
  • WinForm开发中屏蔽WebBrowser脚本错误提示的方法

    2021-06-23 08:49:40
  • Android中TabLayout结合ViewPager实现页面切换效果

    2023-02-03 07:51:05
  • Android ListView 实现上拉加载的示例代码

    2021-09-16 18:04:17
  • JAVA 静态代理模式详解及实例应用

    2021-10-20 05:39:00
  • Java实现的读取资源文件工具类ResourcesUtil实例【可动态更改值的内容】

    2022-01-15 17:27:12
  • C#影院售票系统毕业设计(3)

    2023-04-24 04:08:57
  • Java synchronized重量级锁实现过程浅析

    2023-10-25 14:10:17
  • Java try-catch-finally异常处理机制详解

    2023-10-02 20:29:00
  • Java程序常见异常及处理汇总

    2021-08-12 04:20:44
  • Java实现删除排序数组中重复元素的方法小结【三种方法比较】

    2023-09-28 15:21:48
  • Java实现文件和base64流的相互转换功能示例

    2023-11-18 07:45:01
  • c#的datatable转list示例

    2023-02-14 04:59:58
  • ListView通用泛型适配器

    2022-06-30 11:52:04
  • Android性能优化以及数据优化方法

    2021-09-02 03:46:18
  • C#使用yield关键字让自定义集合实现foreach遍历的方法

    2022-07-21 11:44:28
  • asp之家 软件编程 m.aspxhome.com