Androidstudio中Asset的创建和引用

一、创建:

右击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");
 

摘自:https://blog.csdn.net/shandong_chu/article/details/52779356

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值