当前位置: 移动技术网 > 移动技术>移动开发>Android > Android 遍历文件夹中所有文件的实例代码

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

2019年07月24日  | 移动技术网移动技术  | 我要评论

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

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

/**
   * 获取指定目录内所有文件路径
   * @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;
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网