工程中有一份用於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);
else
copyAssetDirToFiles(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();
}
}