Android 中资源分为两种,一种是res下可编译的资源文件, 这种资源文件系统会在R.Java里面自动生成该资源文件的ID,访问也很简单,只需要调用R.XXX.id即可;第二种就是放在assets文件夹下面的原生资源文件,放在这个文件夹下面的文件不会被R文件编译,所以不能像第一种那样直接使用.Android提供了一个工具类,方便我们操作获取assets文件下的文件:AssetManager

介绍函数
String[] list(String path);//列出该目录下的下级文件和文件夹名称
InputStream open(String fileName);//以顺序读取模式打开文件,默认模式为ACCESS_STREAMING

 InputStream open(String fileName, int accessMode);//以指定模式打开文件。读取模式有以下几种:
//ACCESS_UNKNOWN : 未指定具体的读取模式
//ACCESS_RANDOM : 随机读取
//ACCESS_STREAMING : 顺序读取
//ACCESS_BUFFER : 缓存读取
void close()//关闭AssetManager实例
加载assets目录下的网页
webView.loadUrl("file:///android_asset/html/index.htmll");

说明:这种方式可以加载assets目录下的网页,并且与网页有关的css,js,图片等文件也会的加载。

加载assets目录下的图片资源
InputStream is = getAssets().open(fileName);
bitmap = BitmapFactory.decodeStream(is);
ivImg.setImageBitmap(bitmap);
加载assets目录下文本文件
InputStream is = getAssets().open(fileName);
int lenght = is.available();
byte[] buffer = new byte[lenght];
is.read(buffer);
String result = = new String(buffer, "utf8");
加载assets目录下音乐
// 打开指定音乐文件,获取assets目录下指定文件的AssetFileDescriptor对象
AssetFileDescriptor afd = am.openFd(music);
mPlayer.reset();
// 使用MediaPlayer加载指定的声音文件。
mPlayer.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
// 准备声音
mPlayer.prepare();
// 播放
mPlayer.start();
加载assets目录下视频
private void initview() {
vv = (CustomVideoView) view.findViewById(R.id.videoView111);
//vv.setVideoPath("/mnt/hd/Wonder Girls - Nobody.avi");
Uri uri = copyFile("one.3gp");
vv.setVideoURI(uri);
vv.start();
} public Uri copyFile(String name) {
try {
File dir = getActivity().getFilesDir();
File file = new File(dir, name);
if (file.exists()) {
Log.d("Test", "=========file exist=========");
return Uri.fromFile(file);
} else {
file.createNewFile();
OutputStream os = new FileOutputStream(file);
InputStream is = getActivity().getAssets().open(name);
byte[] buffer = new byte[1024];
int bufferRead = 0;
while((bufferRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bufferRead);
}
os.flush();
is.close();
os.close();
Log.d("Test", "=========copyFile success=========");
return Uri.fromFile(file);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
获取raw目录下的资源 返回流和文件路径
/**
* 获取raw目录下的资源
*
* @param resId 资源id
*/
public static InputStream getRawStream(Context context, int resId) {
return context.getResources().openRawResource(resId); }
/**
* 获取raw目录下的资源
*
* @param resId 资源id
*/
public static String getRawFilePath(Context context, int resId) {
return "android.resource://" + context.getPackageName() + "/" + resId;
}
拷贝assets中文件到指定路径
/**  

从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);
}
}

以下是完整的工具类代码 直接拷贝到工程中就可以使用

package com.insworks.lib_datas.utils;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log; import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream; /**
* @ProjectName: AndroidTemplateProject2
* @Package: com.insworks.lib_datas.utils
* @ClassName: AssetsUtil
* @Author: Song Jian
* @CreateDate: 2019/8/8 14:33
* @UpdateUser: 更新者
* @UpdateDate: 2019/8/8 14:33
* @UpdateRemark: 更新说明
* @Version: 1.0
* @Description: Assets和raw文件文件读取工具类
* <p>
* String[] list(String path);//列出该目录下的下级文件和文件夹名称
* <p>
* InputStream open(String fileName);//以顺序读取模式打开文件,默认模式为ACCESS_STREAMING
* <p>
* InputStream open(String fileName, int accessMode);//以指定模式打开文件。读取模式有以下几种:
* //ACCESS_UNKNOWN : 未指定具体的读取模式
* //ACCESS_RANDOM : 随机读取
* //ACCESS_STREAMING : 顺序读取
* //ACCESS_BUFFER : 缓存读取
*/
public class AssetsUtil {
/**
* 获取assets目录下的网页
* 这种方式可以加载assets目录下的网页,并且与网页有关的css,js,图片等文件也会的加载。
* webView.loadUrl("file:///android_asset/html/index.html");
*
* @param filePath
*/
public static String getHtml(String filePath) {
return "file:///android_asset/" + filePath;
} /**
* 获取所有文件
*
* @param path 目录
* @return
*/
public static String[] getfiles(Context context, String path) {
AssetManager assetManager = context.getAssets();
String[] files = null;
try {
files = assetManager.list(path);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
assetManager.close();
}
return files; } /**
* 获取assets目录下的图片资源
*
* @param fileName
*/
public static Bitmap getPic(Context context, String fileName) {
InputStream is = null;
Bitmap bitmap = null;
try {
is = context.getAssets().open(fileName);
bitmap = BitmapFactory.decodeStream(is); } catch (IOException e) {
e.printStackTrace();
} finally {
close(is);
}
return bitmap;
} /**
* 关闭流
*
* @param is
*/
private static void close(Closeable... is) {
for (Closeable i : is) {
try {
i.close();
} catch (IOException e) {
e.printStackTrace();
}
} } /**
* 获取assets目录下的文本资源
*
* @param fileName
*/
public static String getTex(Context context, String fileName) {
InputStream is = null;
String result = "";
try {
is = context.getAssets().open(fileName);
int lenght = is.available();
byte[] buffer = new byte[lenght];
is.read(buffer);
result = new String(buffer, "utf8");
} catch (IOException e) {
e.printStackTrace();
} finally {
close(is);
}
return result; } /**
* 获取assets目录下的音频资源
*
* @param fileName
*/
public static AssetFileDescriptor getAudio(Context context, String fileName) {
AssetFileDescriptor afd = null;
try {
// 打开指定音乐文件,获取assets目录下指定文件的AssetFileDescriptor对象
afd = context.getAssets().openFd(fileName);
// MediaPlayer mPlayer=new MediaPlayer();
// mPlayer.reset();
// // 使用MediaPlayer加载指定的声音文件。
// mPlayer.setDataSource(afd.getFileDescriptor(),
// afd.getStartOffset(), afd.getLength());
// // 准备声音
// mPlayer.prepare();
// // 播放
// mPlayer.start(); } catch (IOException e) {
e.printStackTrace();
} finally {
close(afd);
}
return afd; } /**
* 获取assets目录下的URI
* 可用于播放视频资源
*
* @param fileName
*/
public static Uri getUri(Context context, String fileName) {
File file = getFile(context, fileName);
//播放视频
// VideoView mVideoView = new VideoView(context);
// mVideoView.setVideoURI(Uri.fromFile(file));
// mVideoView.start();
return Uri.fromFile(file);
} /**
* 将流拷贝到本地 然后返回本地file 默认拷贝到Files目录
*
* @param context
* @param name
* @return
*/
public static File getFile(Context context, String name) {
InputStream is = null;
FileOutputStream os = null;
try {
File dir = context.getFilesDir();
File file = new File(dir, name);
if (file.exists()) {
return file; } else {
file.createNewFile();
os = new FileOutputStream(file);
is = context.getAssets().open(name);
byte[] buffer = new byte[1024];
int bufferRead = 0;
while ((bufferRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bufferRead);
}
os.flush();
is.close();
os.close();
Log.d("Test", "=========getFile success=========");
return file;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
close(is, os);
}
return null;
} /**
* 获取raw目录下的资源
*
* @param resId 资源id
*/
public static InputStream getRawStream(Context context, int resId) {
return context.getResources().openRawResource(resId); } /**
* 获取raw目录下的资源
*
* @param resId 资源id
*/
public static String getRawFilePath(Context context, int resId) {
return "android.resource://" + context.getPackageName() + "/" + resId;
} /**
* 从assets目录中复制内容到sd卡中
*
* @param context Context 使用CopyFiles类的Activity
* @param assetPath String 原文件路径 如:/aa
* @param newPath String 复制后路径 如:xx:/bb/cc
*/
public static void copyFilesFassets(Context context, String assetPath, String newPath) {
InputStream is = null;
FileOutputStream fos = null;
try {
String fileNames[] = context.getAssets().list(assetPath);//获取assets目录下的所有文件及目录名
if (fileNames.length > 0) {//如果是目录
File file = new File(newPath);
file.mkdirs();//如果文件夹不存在,则递归
for (String fileName : fileNames) {
copyFilesFassets(context, assetPath + "/" + fileName, newPath + "/" + fileName);
}
} else {//如果是文件
is = context.getAssets().open(assetPath);
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线程
} finally {
close(is, fos);
}
} }

关于我

私人博客

微信公众号:infree6 或者直接扫码

android 对于asset和raw下文件的操作的更多相关文章

  1. (第三周)wc.exe—命令行实现对指定目录下文件的操作

    一.用户需求 程序处理用户需求的模式为: wc.exe [parameter][filename] 在[parameter]中,用户通过输入参数与程序交互,需实现的功能如下: 1.基本功能 支持 -c ...

  2. Android中asset和raw的区别

    :assets 文件夹是存放不进行编译加工的原生文件,即该文件夹里面的文件不会像 xml, java 文件被预编译,可以存放一些图片,html,js, css 等文件.

  3. Android读写assets、raw、sdard和工程文件的方法

    Android开发离不开对文件的操作,前面的文章“Android简易数据存储之SharedPreferences”和“Android数据存储之SQLite的操作”,分别讲解了简单的数据的存储和数据库数 ...

  4. as3 AIR 添加或删除ApplicationDirectory目录下文件

    AIR的文件目录静态类型有五种: File.userDirectory //指向用户文件夹 File.documentsDirectory //指向用户文档文件夹 File.desktopDirect ...

  5. Android中asset文件夹和raw文件夹区别

    res/raw和assets的相同点: 1.两者目录下的文件在打包后会原封不动的保存在apk包中,不会被编译成二进制. res/raw和assets的不同点: 1.res/raw中的文件会被映射到R. ...

  6. Android中asset文件夹和raw文件夹区别与用法

    *res/raw和assets的相同点: 1.两者目录下的文件在打包后会原封不动的保存在apk包中,不会被编译成二进制. *res/raw和assets的不同点:1.res/raw中的文件会被映射到R ...

  7. Android中asset文件夹与raw文件夹的区别深入解析(转)

    *res/raw和assets的相同点:1.两者目录下的文件在打包后会原封不动的保存在apk包中,不会被编译成二进制.*res/raw和assets的不同点:1.res/raw中的文件会被映射到R.j ...

  8. Android读取asserts和raw文件夹下的文件

    Android读取asserts和raw文件夹下的文件 经常需要用到读取“/res/raw”和"/asserts"文件夹下的文件,索性写成工具类方便以后使用. 一.raw文件夹下的 ...

  9. Android Studio的使用(十)--读取assets、Raw文件夹下文件,以及menu、drawable文件夹

    1.直接在/src/main目录下面新建assets目录 2.接下来即可读取文件 3.读取Raw文件夹下文件也类似.首先在res文件夹下新建raw目录,然后放入需要的文件即可读取. 4.menu和dr ...

随机推荐

  1. centos7安装python3.7.4

    yum install gcc make zlib  zlib-devel openssl openssl-devel libffi-devel bzip2-devel ncurses-devel g ...

  2. Autofac 泛型依赖注入

    using Autofac;using Autofac.Extensions.DependencyInjection;using Hangfire;using Microsoft.AspNetCore ...

  3. styled-components:解决react的css无法作为组件私有样式的问题

    react中的css在一个文件中导入,是全局的,对其他组件标签都会有影响. 使用styled-components第三方模块来解决,并且styled-components还可以将标签和样式写到一起,作 ...

  4. mysql之行转列与列转行

    mysql之行转列与列转行是数据查询的常见操作,以更好的来展示数据,下面就详细说说怎么实现. 行转列 行转列的话,就是将一条一条的行数据记录转换为一条列数据展示,一般来说是根据某一列来做汇总数据的操作 ...

  5. 编译Netty源码遇到的一些问题-缺少io.netty.util.collection包

    缺少包和java类 下载好Netty的源码后,导入到IDE,运行自带的example时编译不通过. 如下图,是因为io.netty.util.collection的包没有 点进去看,确实没有这个包 发 ...

  6. ruby中的多线程和函数的关键字传参

    1.实现ruby中的多线程 # def test1 # n = 1 # if n > 10 # puts "test1结束" # else # while true # sl ...

  7. 文件系统常用命令与fdisk分区

    一.硬盘结构 1.硬盘的逻辑结构 硬盘的大小是使用"磁头数×柱面数×扇区数×每个扇区的大小"这样的公式来计算的.其中磁头数(Heads)表示硬盘总共有几个磁头,也可以理解成为硬盘有 ...

  8. C#使用Linq to csv读取.csv文件数据

    前言:今日遇到了一个需要读取CSV文件类型的EXCEL文档数据的问题,原本使用NPOI的解决方案直接读取文档数据,最后失败了,主要是文件的类型版本等信息不兼容导致.其他同事有使用linq to csv ...

  9. Ligg.EasyWinApp-101-Ligg.EasyWinForm: Application--启动,传入参数、读取Application级别配置文件、验证密码、软件封面、启动登录、StartForm

    首先请在VS里打开下面的文件,我们将对源码分段进行说明: 步骤1:读取debug.ini文件 首先读取当前文件夹(.\Clients\Form)的debug.ini文件,该文件的args用于调试时传参 ...

  10. C++常用的string字符串截断函数

    C++中经常会用到标准库函数库(STL)的string字符串类,跟其他语言的字符串类相比有所缺陷.这里就分享下我经常用到的两个字符串截断函数: #include <iostream> #i ...