Today, we are studying how to obtain folder files in Android.ProgramYou need to traverse the specified directory or global directory of Android to obtain the files in the directory. However, when getting the files, you may encounter the problem that the files in the folder cannot be listed. this is my problem, when listfiles () is obtained for a sub-folder, the returned value is null, that is, the contents in the folder cannot be listed. This is due to the security mechanism in Android. Because Android inherits the tradition of Linux, there are three types of permissions for a specific directory: readable, writable, and executable; although we can set permissions for a specific directory, we can set permissions for sub-directories and sub-files in the directory, that is, out of the root directory permissions, the sub-directory permission also determines whether the Sub-directory can be accessed. Therefore, we need to perform listfiles () after obtaining file [] data, check whether the obtained array is empty. If it is empty, the folder is inaccessible. ExampleCodeAs follows:
Package Com. zys. file;
Import Java. Io. file;
Import Java. util. arraylist;
Import Java. util. hashmap;
Import Java. util. Map;
Import Android. util. log;
/**
* @ Author
* Function is used to scan files on the SD card.
*
*/
Public Class Filescan {
Private Static Final String tag = " Filescan " ;
Public Hashmap < String, string > Getmusiclistonsys (File file ){
// Scan from the root directory
Log. I (TAG, file. getpath ());
Hashmap < String, string > Filelist = New Hashmap < String, string > ();
Getfilelist (file, filelist );
Return Filelist;
}
/**
* @ Param Path
* @ Param Filelist
* Note that not all folders can be read. Permission Problems
*/
Private Void Getfilelist (file path, hashmap < String, string > Filelist ){
// If it is a folder
If (Path. isdirectory ()){
// Return the data in the folder.
File [] files = Path. listfiles ();
// First, check whether there is any permission. If there is no permission, it will not be executed.
If ( Null = Files)
Return ;
For ( Int I = 0 ; I < Files. length; I ++ ){
Getfilelist (files [I], filelist );
}
}
// Add files directly
Else {
Log. I (TAG, path. getabsolutepath ());
// Process files
String filepath = Path. getabsolutepath ();
// File Name
String filename = Filepath. substring (filepath. lastindexof ( " / " ) + 1 );
// Add
Filelist. Put (filename, filepath );
}
}
}