前言
這幾天遇到了一個坑!關于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();
}