简体   繁体   English

如何列出Android设备内部目录中指定文件夹中的文件

[英]how to list, files from a specified folder in the internal directory of android device

我需要显示目录 示例中 指定文件夹中的文件 ,根路径为Directory:/ sdcard / GDM /如何从该文件夹中列出文件。

The File class provides you with a list() method: File类为您提供了一个list()方法:

Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname. 返回一个字符串数组,命名该抽象路径名表示的目录中的文件和目录。 If this abstract pathname does not denote a directory, then this method returns null. 如果此抽象路径名不表示目录,则此方法返回null。 Otherwise an array of strings is returned, one for each file or directory in the directory. 否则,将返回一个字符串数组,该字符串数组用于目录中的每个文件或目录。 Names denoting the directory itself and the directory's parent directory are not included in the result. 结果中不包括表示目录本身和目录的父目录的名称。 Each string is a file name rather than a complete path. 每个字符串都是文件名,而不是完整的路径。

There is no guarantee that the name strings in the resulting array will appear in any specific order; 不能保证结果数组中的名称字符串会以任何特定顺序出现; they are not, in particular, guaranteed to appear in alphabetical order. 尤其不能保证它们按字母顺序出现。

So, the code will be something like: 因此,代码将类似于:

File root = new File("/sdcard/GDM");
String[] files = root.list();  
if( files != null ){
 // do something
}  

Update(s): 更新):
To get the size of the file, you will need the length() method. 要获取文件的大小,您将需要使用length()方法。 This will return the size in bytes. 这将返回字节大小。 If you want to get it in MBs, you will need to divide it by 1024*1024 如果要以MB为单位获取,则需要将其除以1024*1024

File f = new File("/path/to/some/file");
double sizeInMb = f.length() / (1024*1024);

To get list of files from your sdcard, 要从您的SD卡中获取文件列表,

List<File> listFilesRoot = getFilesFromRoot(new File("YOUR PATH"));


private List<File> getFilesFromRoot(File parentDir) {
        ArrayList<File> listFiles = new ArrayList<File>();
        File[] files = parentDir.listFiles();
        for (File file : files) {
            if (!file.isDirectory())  {
                    listFiles.add(file);
            }
        }
        return listFiles;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM