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

文章介绍了如何在Android应用中,将用于WebView显示的静态文件从Asset目录拷贝至私有Files目录,并修改WebView加载路径,以实现文件的动态更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

工程中有一份用于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();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值