资源放在assets文件夹中如何获得其绝对路径【android】
assets文件夹中的文件会随着APP的安装,存放在路径:/data/data/com.example.camera(你的程序包名)/files/文件名例如:path=/data/data/com.example.camera/files/liu.jpgpath=/data/data/com.example.camera/files/yz.jpg获取该路径的方法如下://获取工具类p...
·
assets文件夹中的文件会随着APP的安装,存放在路径:/data/data/com.example.camera(你的程序包名)/files/文件名
例如:
path=/data/data/com.example.camera/files/liu.jpg
path=/data/data/com.example.camera/files/yz.jpg
获取该路径的方法如下:
//获取工具类
package com.example.camera;
import android.content.Context;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class FileUtils {
public static String getModelFilePath(Context context, String modelName) {
copyFileIfNeed(context,modelName);
return context.getFilesDir().getAbsolutePath() + File.separator + modelName;
}
/**
* 拷贝asset下的文件到context.getFilesDir()目录下
*/
private static void copyFileIfNeed(Context context, String modelName) {
InputStream is = null;
OutputStream os = null;
try {
// 默认存储在data/data/<application name>/file目录下
File modelFile = new File(context.getFilesDir(), modelName);
is = context.getAssets().open(modelName);
if (modelFile.length() == is.available()) {
return;
}
os = new FileOutputStream(modelFile);
byte[] buffer = new byte[1024];
int length = is.read(buffer);
while (length > 0) {
os.write(buffer, 0, length);
length = is.read(buffer);
}
os.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
//使用方法:
String path=FileUtils.getModelFilePath(context, imgName);
Log.d(TAG,"path="+path);
String path=FileUtils.getModelFilePath(context, "yz.jpg");//获取assets文件夹下名为"yz.jpg"的图片路径
Log.d(TAG,"path="+path);//打印该路径
//运行结果
path=/data/data/com.example.camera/files/yz.jpg
更多推荐
已为社区贡献2条内容
所有评论(0)