一、创建:
右击app->new->Folder->Assets Folder.
这样就在main文件夹下创建了一个和res文件夹同级的assets文件夹了:
二、使用:
1.加载assets目录下的网页
//加载assets/win8_Demo/目录下的index.html网页
webView.loadUrl(”file:///android_asset/win8_Demo/index.html”);
说明:这种方式可以加载assets目录下的网页,并且与网页有关的css,js,图片等文件也会加载。
2.访问assets目录下的资源文件:
// 读取Assets文件夹下对应文件的输入流
InputStream is = getAssets().open("asset_test.txt");
// 读取Assets文件夹下mysw文件夹内对应文件的输入流
InputStream is2 = getAssets().open("mysw/asset_test.txt");
3.获取assets的文件及目录名
String fileNames[] =context.getAssets().list(path);
4.将assets下的文件复制到SD卡
/**
* 从assets目录中复制整个文件夹内容
* @param context Context 使用CopyFiles类的Activity
* @param oldPath String 原文件路径 如:/aa
* @param newPath String 复制后路径 如:xx:/bb/cc
*/
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) {
// TODO Auto-generated catch block
e.printStackTrace();
//如果捕捉到错误则通知UI线程
MainActivity.handler.sendEmptyMessage(COPY_FALSE);
}
}
最后该方法调用时的代码:music为assets目录下面的文件夹,里面包括具体的文件
copyFilesFassets(this, "music", "sdcard/clock");