android asset到/data/data/PACKAGE/files的文件夹拷贝

来源:互联网 发布:js裁剪图片并上传 编辑:程序博客网 时间:2024/05/28 06:07

工程中有一份用于WebView显示的静态文件,将其放到asset目录下,而后续需求中又需要定期的从服务器获取部分有更新文件,而asset下的文件是只读的,无法将从服务器端获取的最新文件写入到asset下,因此决定将静态文件打包进asset目录中,当第一次启动时,从asset中拷贝到app的私有目录files下,以后就只对files中文件进行更新,使用WebView加载文件时也使用files中的文件。

之前从asset中加载的方法为:

webView.loadUrl("file:///android_asset/www/" + filename);

现在改为:

webView.loadUrl("file://" + getFilesDir() + "/www/" + filename);

从asset到files的文件拷贝代码如下:

import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import android.content.Context;import android.content.res.AssetManager;public class FileUtils {public static void copyAssetDirToFiles(Context context, String dirname)throws IOException {File dir = new File(context.getFilesDir() + "/" + dirname);dir.mkdir();AssetManager assetManager = context.getAssets();String[] children = assetManager.list(dirname);for (String child : children) {child = dirname + '/' + child;String[] grandChildren = assetManager.list(child);if (0 == grandChildren.length)copyAssetFileToFiles(context, child);elsecopyAssetDirToFiles(context, child);}}public static void copyAssetFileToFiles(Context context, String filename)throws IOException {InputStream is = context.getAssets().open(filename);byte[] buffer = new byte[is.available()];is.read(buffer);is.close();File of = new File(context.getFilesDir() + "/" + filename);of.createNewFile();FileOutputStream os = new FileOutputStream(of);os.write(buffer);os.close();}}
原创粉丝点击