从资产文件夹中获取仅扩展名为 .txt 的文件的文件名

Get File names from assets folder for files only with .txt extension

目前我有这个代码:

ArrayList<String> items = new ArrayList<String>();
                AssetManager assetManager = getApplicationContext().getAssets();
                try {
                     items.addAll(Arrays.asList(assetManager.list("")));
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

这为我提供了资产文件夹中所有文件名的数组列表。 但是我需要对此进行过滤,以便 arraylist 仅包含具有 .txt 扩展名的文件的文件名,然后从每个项目名称中删除 .txt。

因此当前代码将导致:

test.txt
pi.txt
sounds
hippo.png
square.xml
seven.txt

但当我需要时,arraylist 的内容将是:

test 
pi 
seven

所以你需要做

ArrayList<String> items = new ArrayList<String>();
AssetManager assetManager = getApplicationContext().getAssets();
for (String file : assetManager.list("")) {
    if (file.endsWith(".txt"))
        items.add(file);
}

如果您想从文件名中删除 .txt 扩展名,您可以这样做

...
    items.add(file.replaceAll(".txt$", ""));
...