0

Is there any way to access a file into assets folder by name with regular expression?

Only selected one file but obvious the suffix into the name

Something like:

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

The case:

      /assets/box_1223.png
StarsSky
  • 6,721
  • 6
  • 38
  • 63
Zeus Monolitics
  • 832
  • 9
  • 19

4 Answers4

2

Just walk through the list...

for( String fileName : getAssets().list( "" ) ) {
    if( fileName.endsWith( ".png" ) ) {
        // here's your image
    }
}
323go
  • 14,143
  • 6
  • 33
  • 41
1

You should get all files from assets folder

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
        }
    }

You can view all files and take only what you need, by using REGEX or contains()

StarsSky
  • 6,721
  • 6
  • 38
  • 63
0

I wrote this code for get a file path name from assets directory by regular expresion:

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;
}
Zeus Monolitics
  • 832
  • 9
  • 19
0

I found you need to recurse through the assets folder if you have created directories within it.

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 + "\"");
    }
}

Then I kicked this off by searching for top level assets by passing an empty string

listAssets("", 1);
Brent K.
  • 927
  • 1
  • 11
  • 16