可以獲得文件夾中所有文件的路徑及文件名。
代碼很簡單,直接上車,車上再解釋:
/** * 獲取指定目錄內所有文件路徑 * @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; }以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答