android raw 引用,Android 资源-raw和assets
前言
這幾天遇到了一個坑!關(guān)于resource相關(guān)的操作。具體的需求是:替換所有班級的logo,但是移動端android和ios沒有建立協(xié)議,所以臨時采用的是直接上傳圖片來完成這項(xiàng)任務(wù)。當(dāng)然一個項(xiàng)目有很多人開發(fā),之前的功能已經(jīng)實(shí)現(xiàn)了根據(jù)文件的URI來上傳具體的File。
問題來了:怎么才能讀取到android res 具體的File呢?
認(rèn)識res
1. res/raw和assets的區(qū)別?
共同點(diǎn):res/raw和assets這兩個目錄下的文件都會被打包進(jìn)APK,并且不經(jīng)過任何的壓縮處理。
不同點(diǎn):assets支持任意深度的子目錄,這些文件不會生成任何資源ID,只能使用AssetManager按相對的路徑讀取文件。如需訪問原始文件名和文件層次結(jié)構(gòu),則可以考慮將某些資源保存在assets目錄下。
解決問題
copy
可以對Android 的 res 和 assets 里面的文件進(jìn)行拷貝。我封裝了兩個方法。
/**
* 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; //每次讀的字節(jié)數(shù)
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; //每次讀的字節(jié)數(shù)
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();
}
總結(jié)
以上是生活随笔為你收集整理的android raw 引用,Android 资源-raw和assets的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 从零开始学Qt - 05:设置图标、打包
- 下一篇: android cpu hotplug,