Android从assets目录下读取文件相关

有一个需求是app的帮助文档是word格式,ios可以直接用webview加载word显示,Android不行。而美工不配合转换成图片,前端没时间把word写成html

没办法,自己搞。

步骤:

 1、用第三方靠谱的软件把word文档转成html。

 2、放入assets目录下,用webview进行加载。

 3、然后你会发现里面的图片显示不了,傻眼了,为什么?? html的image标签中src指向的地址中没有图片资源啊。你的工程中没有图片资源啊,怎么办?

 4、可以把图片存入工程中,或者本地等等,然后改html中的src路径。 但是。。。。。俺家的帮助文档有200张图片。一条条改真的好吗。

 5、解决方案:把图片放入assets目录下的一个文件夹中。然后命名要跟html中的图片命名相同,然后利用webview动态加载显示。代码如下

 public void setWebViewListener() {
//不调用系统浏览器
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public void onPageCommitVisible(WebView view, String url) {
                super.onPageCommitVisible(view, url);
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String request) {//主要是用的这个方法,这个方法会在每次读取图片的时候回调,
//只要在这个时候返回要的图片即可,之前之所以把图片的名字命名成跟html中一样的是为了少写代码
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { LogUtils.logInfoStar(request+"返回的request"); } AssetManager am = getResources().getAssets(); InputStream is = null; // String[] helpimgs = GetAssetsFiles.getfilesFromAssets(mContext, "helpimg"); String substring = request.substring(request.lastIndexOf("/")+1,request.lastIndexOf(".")); try { is = am.open("helpimg/"+substring+".png"); WebResourceResponse res=new WebResourceResponse("text/html","utf-8",is); return res; } catch (IOException e) { e.printStackTrace(); } return super.shouldInterceptRequest(view, request); } });

以下是总结的从assets目录中读取文件的工具类,请看详细注释:

package com.create.bicdroid.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.create.utilslibrary.LogUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by Administrator on 2016/11/21.
 */
public class GetAssetsFiles {
    /**
     * 获取assets目录下的图片
     *
     * @param context
     * @param fileName
     * @return
     */
    public static Bitmap getImageFromAssetsFile(Context context, String fileName) {
        Bitmap image = null;
        AssetManager am = context.getResources().getAssets();
        try {
            InputStream is = am.open(fileName);
            image = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return image;
    }

    /**
     * 获取assets目录下的单个文件
     *
     * @param context
     * @param fileName
     * @return
     */
    public static File getFileFromAssetsFile(Context context, String fileName) {//这种方式不能用,只能用于webview加载,直接取路径是不行的

        String path = "file:///android_asset/" + fileName;
        File file = new File(path);
        return file;

    }

    /**
     * 获取所有文件
     *
     * @param path
     * @return
     */
    public static String[] getfilesFromAssets(Context context, String path) {
        AssetManager assetManager = context.getAssets();
        String[] files = null;
        try {
            files = assetManager.list(path);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        for (String str : files) {
            LogUtils.logInfoStar(str);
        }
        return files;

    }

    /**
     * 将assets下的文件放到sd指定目录下
     *
     * @param context    上下文
     * @param assetsPath assets下的路径
     * @param sdCardPath sd卡的路径
     */
    public static void putAssetsToSDCard(Context context, String assetsPath,
                                         String sdCardPath) {
        try {
            String mString[] = context.getAssets().list(assetsPath);
            if (mString.length == 0) { // 说明assetsPath为空,或者assetsPath是一个文件
                InputStream mIs = context.getAssets().open(assetsPath); // 读取流
                byte[] mByte = new byte[1024];
                int bt = 0;
                File file = new File(sdCardPath + File.separator
                        + assetsPath.substring(assetsPath.lastIndexOf('/')));
                if (!file.exists()) {
                    file.createNewFile(); // 创建文件
                } else {
                    return;//已经存在直接退出
                }
                FileOutputStream fos = new FileOutputStream(file); // 写入流
                while ((bt = mIs.read(mByte)) != -1) { // assets为文件,从文件中读取流
                    fos.write(mByte, 0, bt);// 写入流到文件中
                }
                fos.flush();// 刷新缓冲区
                mIs.close();// 关闭读取流
                fos.close();// 关闭写入流

            } else { // 当mString长度大于0,说明其为文件夹
                sdCardPath = sdCardPath + File.separator + assetsPath;
                File file = new File(sdCardPath);
                if (!file.exists())
                    file.mkdirs(); // 在sd下创建目录
                for (String stringFile : mString) { // 进行递归
                    putAssetsToSDCard(context, assetsPath + File.separator
                            + stringFile, sdCardPath);
                }
            }
        } catch (
                Exception e
                )

        {
            e.printStackTrace();
        }
    }


}
原文地址:https://www.cnblogs.com/epmouse/p/6144098.html