Android 获取 Assets 目录下文件路径的方法
可以使用下面的代码来获取 assets 目录下指定文件的路径:
public String getAssetFilePath(Context context, String fileName) {
AssetManager assetManager = context.getAssets();
String filePath = null;
try {
String[] files = assetManager.list("");
for (String file : files) {
if (file.equals(fileName)) {
filePath = context.getCacheDir().getAbsolutePath() + "/" + fileName;
File outFile = new File(filePath);
InputStream in = assetManager.open(file);
OutputStream out = new FileOutputStream(outFile);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
out.flush();
out.close();
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return filePath;
}
这个方法首先获取 AssetManager 对象,然后遍历 assets 目录下的文件,找到指定的文件名后,将文件复制到应用的缓存目录中,并返回该文件的路径。注意,这个方法需要在子线程中执行,以避免阻塞 UI 线程。
原文地址: https://www.cveoy.top/t/topic/ovS5 著作权归作者所有。请勿转载和采集!