可以獲得文件夾中所有文件的路徑及文件名纪隙。
代碼很簡單遍膜,直接上車碗硬,車上再解釋:
/**
* 獲取指定目錄內(nèi)所有文件路徑
* @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){//判斷權(quán)限
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;
}