android raw 引用,Android 资源-raw和assets

前言

这几天遇到了一个坑!关于resource相关的操作。具体的需求是:替换所有班级的logo,但是移动端android和ios没有建立协议,所以临时采用的是直接上传图片来完成这项任务。当然一个项目有很多人开发,之前的功能已经实现了根据文件的URI来上传具体的File。

问题来了:怎么才能读取到android res 具体的File呢?

认识res

1. res/raw和assets的区别?

共同点:res/raw和assets这两个目录下的文件都会被打包进APK,并且不经过任何的压缩处理。

不同点:assets支持任意深度的子目录,这些文件不会生成任何资源ID,只能使用AssetManager按相对的路径读取文件。如需访问原始文件名和文件层次结构,则可以考虑将某些资源保存在assets目录下。

解决问题

copy

可以对Android 的 res 和 assets 里面的文件进行拷贝。我封装了两个方法。

/**

* copy asset to

*

* @param context

* @param fileName

*/

public static void copyAssetsToOutterByFileName(final Context context, final String fileName) {

//getFilesDir,指/data/data//files/

final File filedir = new File(context.getFilesDir() + "/classlogo");

if (!filedir.exists()) {

filedir.mkdir();

}

final File file = new File(filedir, fileName);

if (file.exists()) {

Logger.t(TAG).i(fileName + "文件存在,无需拷贝");

return;

}

new Thread() {

@Override

public void run() {

InputStream is = null;

OutputStream fos = null;

try {

is = context.getAssets().open(fileName);

fos = new FileOutputStream(file);

//缓存

byte[] b = new byte[2 * 1024];

int len; //每次读的字节数

while ((len = is.read(b)) != -1) {

if (fos != null) {

fos.write(b, 0, len);

}

}

fos.close();

is.close();

Logger.t(TAG).i(fileName + "文件拷贝完成");

} catch (IOException e) {

Logger.t(TAG).i(fileName + "文件拷贝失败");

e.printStackTrace();

} finally {

closeQuietly(fos);

closeQuietly(is);

}

}

}.start();

}

/**

* @param context

* @param fileName

* @param type "drawable" "raw"

*/

public static void copyResToOutterByFileName(final Context context, final String fileName, final String type) {

//getFilesDir,指/data/data//files/

final File filedir = new File(context.getFilesDir() + "/classlogo");

if (!filedir.exists()) {

filedir.mkdir();

}

final File file = new File(filedir, fileName);

if (file.exists()) {

Logger.t(TAG).i(fileName + "文件存在,无需拷贝");

return;

}

new Thread() {

@Override

public void run() {

InputStream is = null;

OutputStream fos = null;

try {

int resId = context.getResources().getIdentifier(fileName, type, context.getPackageName());

is = context.getResources().openRawResource(resId);

fos = new FileOutputStream(file);

//缓存

byte[] b = new byte[2 * 1024];

int len; //每次读的字节数

while ((len = is.read(b)) != -1) {

if (fos != null) {

fos.write(b, 0, len);

}

}

fos.close();

is.close();

Logger.t(TAG).i(fileName + "文件拷贝完成,文件地址:" + file.getAbsolutePath());

} catch (IOException e) {

Logger.t(TAG).i(fileName + "文件拷贝失败");

e.printStackTrace();

} finally {

closeQuietly(fos);

closeQuietly(is);

}

}

}.start();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值