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

Android开发求助:统计文件夹文件数仅返回子文件夹数,文件未被识别

问题解决:统计文件夹文件数量返回0的原因及修复

1. 先查权限——最常见的坑

Android 6.0之后需要动态申请读存储权限,Android 10及以上还要额外配置才能继续使用传统文件访问方式:

  • 在AndroidManifest.xml中添加权限声明:
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <!-- Android 10+ 需添加该属性,才能用File API访问自定义目录 -->
    <application
        ...
        android:requestLegacyExternalStorage="true">
    
  • 在代码中动态申请权限:
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                1001);
    }
    

2. Android 10+分区存储限制,File API无法读取全部文件

从Android 10开始,系统默认启用分区存储,直接通过File API访问Download目录下的自定义子文件夹,可能无法获取到所有文件,此时需要改用MediaStore API查询:

public int getJpgFilesCount() {
    ContentResolver resolver = getContentResolver();
    Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    
    // 筛选Download/RubikaDownloaders目录下的jpg格式文件
    String selection = MediaStore.Images.Media.RELATIVE_PATH + " LIKE ? AND " + MediaStore.Images.Media.MIME_TYPE + " = ?";
    String[] selectionArgs = new String[]{
            "%Download/RubikaDownloaders%",
            "image/jpeg"
    };
    
    Cursor cursor = resolver.query(uri, null, selection, selectionArgs, null);
    int count = cursor != null ? cursor.getCount() : 0;
    if (cursor != null) cursor.close();
    return count;
}

3. 先验证目录是否可访问

在你的getFilesCount方法中添加验证逻辑,确认目录状态:

public int getFilesCount(String folder) {
    File directory = new File(folder);
    // 检查目录是否存在且具备读取权限
    if (!directory.exists() || !directory.canRead()) {
        Log.i("mytag", "目录不存在或无读取权限");
        return 0;
    }
    File[] files = directory.listFiles();
    if (files == null)
        return 0;
    // 打印每个项的类型,确认是否识别到jpg文件
    for (File file : files)
        Log.i("mytag", "name=" + file.getName() + " | 是文件?" + file.isFile());
    return files.length;
}

如果日志中看不到目标jpg文件,说明是权限或存储机制问题,对应上面的方法调整即可。

额外提醒

  • Android 11及以上,即使申请了READ_EXTERNAL_STORAGE权限,File API也可能无法访问自定义子文件夹,优先使用MediaStore或SAF(存储访问框架)。
  • 确认代码中的文件路径与文件管理器显示的完全一致,注意大小写、斜杠方向等细节。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 03:12:41