欢迎来到代码驿站!

Android代码

当前位置:首页 > 移动开发 > Android代码

Android 遍历文件夹中所有文件的实例代码

时间:2021-04-22 09:14:19|栏目:Android代码|点击:

可以获得文件夹中所有文件的路径及文件名。

代码很简单,直接上车,车上再解释:

/**
   * 获取指定目录内所有文件路径
   * @param dirPath 需要查询的文件目录
   * @param _type 查询类型,比如mp3什么的
   */
  public static JSONArray getAllFiles(String dirPath, String _type) {
    File f = new File(dirPath);
    if (!f.exists()) {//判断路径是否存在
      return null;
    }

    File[] files = f.listFiles();

    if(files==null){//判断权限
      return null;
    }

    JSONArray fileList = new JSONArray();
    for (File _file : files) {//遍历目录
      if(_file.isFile() && _file.getName().endsWith(_type)){
        String _name=_file.getName();
        String filePath = _file.getAbsolutePath();//获取文件路径
        String fileName = _file.getName().substring(0,_name.length()-4);//获取文件名
//        Log.d("LOGCAT","fileName:"+fileName);
//        Log.d("LOGCAT","filePath:"+filePath);
        try {
          JSONObject _fInfo = new JSONObject();
          _fInfo.put("name", fileName);
          _fInfo.put("path", filePath);
          fileList.put(_fInfo);
        }catch (Exception e){
        }
      } else if(_file.isDirectory()){//查询子目录
        getAllFiles(_file.getAbsolutePath(), _type);
      } else{
      }
    }
    return fileList;
  }

上一篇:Android Recyclerview实现多选,单选,全选,反选,批量删除的功能

栏    目:Android代码

下一篇:Android自定义滑动验证条的示例代码

本文标题:Android 遍历文件夹中所有文件的实例代码

本文地址:http://www.codeinn.net/misctech/106617.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有