You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Android应用shared_prefs目录下筛选名称以note_开头的文件

实现方案

你可以直接使用File#list(FilenameFilter)方法在列出文件时直接完成过滤,无需二次遍历,代码如下:

File f = new File("/data/data/com.bhiruva/shared_prefs/");
// 过滤器实现:匹配文件名前缀,这里做了小写转换适配大小写不同的命名情况
String[] pathnames = f.list((dir, fileName) -> fileName.toLowerCase().startsWith("note_"));

如果你的文件名固定为大写Note_开头,不需要兼容小写场景,直接去掉toLowerCase()即可:

String[] pathnames = f.list((dir, fileName) -> fileName.startsWith("Note_"));

注意事项

  • 必须对list()的返回值做判空处理,当目标目录不存在、无读取权限、路径指向非目录对象时,list()会返回null,直接操作会触发空指针异常。
  • 如果需要兼容低版本Android(对应Java 7及更低版本API),可以用普通遍历的方式实现过滤:
File f = new File("/data/data/com.bhiruva/shared_prefs/");
String[] allFiles = f.list();
List<String> targetFiles = new ArrayList<>();
if (allFiles != null) {
    for (String name : allFiles) {
        if (name.toLowerCase().startsWith("note_")) {
            targetFiles.add(name);
        }
    }
}
// 如需转回数组可使用:targetFiles.toArray(new String[0])

内容的提问来源于stack exchange,提问作者user16257123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 19:24:07