android获取assets资源

android获取assets资源

1.加载assets目录下的网页

webView.loadUrl("file:///android_asset/Demo1/index.html");

2.访问assets目录下的资源文件

String name = "hallo.txt";
    InputStream resourceAsStream = getClass().getResourceAsStream("/assets/" + name);

3.获取assets的文件及目录名

String fileNames[] =context.getAssets().list(path);

4.将assets下的文件复制到SD卡

public void copyFilesFassets(Context context, String oldPath, String newPath) {

        try {
            String fileNames[] = context.getAssets().list(oldPath);//获取assets目录下的所有文件及目录名
            if (fileNames.length > 0) {//如果是目录
                File file = new File(newPath);
                file.mkdirs();//如果文件夹不存在,则递归
                for (String fileName : fileNames) {
                    copyFilesFassets(context, oldPath + "/" + fileName, newPath + "/" + fileName);
                }
            } else {//如果是文件
                InputStream is = context.getAssets().open(oldPath);
                FileOutputStream fos = new FileOutputStream(new File(newPath));
                byte[] buffer = new byte[1024];
                int byteCount = 0;
                while ((byteCount = is.read(buffer)) != -1) {//循环从输入流读取 buffer字节
                    fos.write(buffer, 0, byteCount);//将读取的输入流写入到输出流
                }
                fos.flush();//刷新缓冲区
                is.close();
                fos.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

猜你喜欢

转载自blog.csdn.net/AliEnCheng/article/details/78445364