我的Android应用程序在资产目录中有一些文件,我想在启动时打开,方法是列出目录中的文件并打开每个文件.我正在尝试使用AssetManager来执行此操作,但它似乎没有像我期望的那样.我的示例代码如下.这是正确的方法还是有更好的方法来做到这一点?
我使用以下方法打印出资产目录树.
void displayFiles (AssetManager mgr, String path) {
try {
String list[] = mgr.list(path);
if (list != null)
for (int i=0; i<list.length; ++i)
{
Log.v("Assets:", path +"/"+ list[i]);
displayFiles(mgr, path + list[i]);
}
} catch (IOException e) {
Log.v("List error:", "can't list" + path);
}
}
Run Code Online (Sandbox Code Playgroud)
从我的Activity的onCreate方法中,我执行以下操作:
final AssetManager mgr = getAssets();
displayFiles(mgr, "/assets");
displayFiles(mgr, "./assets");
displayFiles(mgr, "/");
displayFiles(mgr, "./");
Run Code Online (Sandbox Code Playgroud)
这给了我以下输出
09-29 20:08:27.843: DEBUG/GFlash(6543): //AndroidManifest.xml 09-29 20:08:27.954: DEBUG/GFlash(6543): //META-INF 09-29 20:08:28.063: DEBUG/GFlash(6543): //assets 09-29 20:08:28.233: DEBUG/GFlash(6543): //classes.dex 09-29 20:08:28.383: DEBUG/GFlash(6543): //com 09-29 20:08:28.533: DEBUG/GFlash(6543): //res 09-29 20:08:28.683: DEBUG/GFlash(6543): //resources.arsc
提前致谢!
约翰
Joh*_* MD 13
啊.问题出在displayFiles方法中,它缺少目录和文件名之间的分隔符"/".对不起,如果我浪费了任何人的时间.下面是displayFiles的更正版本.
void displayFiles (AssetManager mgr, String path) {
try {
String list[] = mgr.list(path);
if (list != null)
for (int i=0; i<list.length; ++i)
{
Log.v("Assets:", path +"/"+ list[i]);
displayFiles(mgr, path + "/" + list[i]);
}
} catch (IOException e) {
Log.v("List error:", "can't list" + path);
}
}
Run Code Online (Sandbox Code Playgroud)
约翰
小智 11
要完全递归,您可以按如下方式更新方法:
void displayFiles (AssetManager mgr, String path, int level) {
Log.v(TAG,"enter displayFiles("+path+")");
try {
String list[] = mgr.list(path);
Log.v(TAG,"L"+level+": list:"+ Arrays.asList(list));
if (list != null)
for (int i=0; i<list.length; ++i)
{
if(level>=1){
displayFiles(mgr, path + "/" + list[i], level+1);
}else{
displayFiles(mgr, list[i], level+1);
}
}
} catch (IOException e) {
Log.v(TAG,"List error: can't list" + path);
}
}
Run Code Online (Sandbox Code Playgroud)
然后打电话:
final AssetManager mgr = applicationContext.getAssets();
displayFiles(mgr, "",0);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19879 次 |
| 最近记录: |