0

有什么方法可以使用正则表达式按名称将文件访问到资产文件夹中?

只选择了一个文件,但名称中的后缀很明显

就像是:

    aFD =SessionManager.getAppContext().getAssets().openFd("box*.png");

案子:

      /assets/box_1223.png
4

4 回答 4

2

只需浏览列表...

for( String fileName : getAssets().list( "" ) ) {
    if( fileName.endsWith( ".png" ) ) {
        // here's your image
    }
}
于 2013-02-01T15:13:04.390 回答
1

您应该从 assets 文件夹中获取所有文件

AssetManager amgr = getAssets();
    String[] list = amgr.list("./");
    for(String s : list){
        Log.d("File:", s);
        //check if filename is what you need
        if (s.contains(what you need OR regex pattern)){
            //do staff
        }
    }

您可以查看所有文件并仅获取您需要的文件,方法是使用REGEXcontains()

于 2013-02-01T15:13:38.623 回答
0

我编写了这段代码,用于通过正则表达式从资产目录中获取文件路径名:

public String getFileNameFromAssetsByExpresion(String dirFrom, String nameExp) {
AssetManager am = SessionManager.getAppContext().getAssets();
String nameRetExp = null;
try {
    for (String s : am.list(dirFrom)) {
    // check if filename is what you need
    if (Pattern.matches(nameExp, s)) { nameRetExp = s; break;}
    }
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
return nameRetExp;
}
于 2013-02-01T16:38:03.330 回答
0

如果您在其中创建了目录,我发现您需要通过 assets 文件夹进行递归。

private void listAssets(String startPath, int level) {
    try {
        for(String s : getAssets().list(startPath)){
            Log.d(TAG, "Level " + level + " asset found: " + s);
            if (Pattern.matches(nameExp, s)) { 
               // TODO: Handle the asset matching the regex here!
            }    

            // Recursively call ourself, one level deeper
            String newPath = s;
            if(startPath.length() > 0) {
                newPath = startPath + "/" + s;
            }
            listAssets(newPath, level + 1);
        }
    } catch (IOException e) {
        Log.d(TAG, "No assets for: \"" + startPath + "\"");
    }
}

然后我通过传递一个空字符串来搜索顶级资产

listAssets("", 1);
于 2021-06-02T16:32:27.920 回答