Android 遍历文件夹中所有文件的实例代码
可以获得文件夹中所有文件的路径及文件名。
代码很简单,直接上车,车上再解释:
/** *获取指定目录内所有文件路径 *@paramdirPath需要查询的文件目录 *@param_type查询类型,比如mp3什么的 */ publicstaticJSONArraygetAllFiles(StringdirPath,String_type){ Filef=newFile(dirPath); if(!f.exists()){//判断路径是否存在 returnnull; } File[]files=f.listFiles(); if(files==null){//判断权限 returnnull; } JSONArrayfileList=newJSONArray(); for(File_file:files){//遍历目录 if(_file.isFile()&&_file.getName().endsWith(_type)){ String_name=_file.getName(); StringfilePath=_file.getAbsolutePath();//获取文件路径 StringfileName=_file.getName().substring(0,_name.length()-4);//获取文件名 //Log.d("LOGCAT","fileName:"+fileName); //Log.d("LOGCAT","filePath:"+filePath); try{ JSONObject_fInfo=newJSONObject(); _fInfo.put("name",fileName); _fInfo.put("path",filePath); fileList.put(_fInfo); }catch(Exceptione){ } }elseif(_file.isDirectory()){//查询子目录 getAllFiles(_file.getAbsolutePath(),_type); }else{ } } returnfileList; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。