12


我在 SD 卡中有一个文件夹,其中包含多个文件。现在我需要获取这些文件的名称。有人知道如何获取存储在 SD 卡中的文件名吗?

任何帮助将不胜感激。多谢。

4

5 回答 5

24

Environment.getExternalStorageDirectory会给你一个File对应的SDCARD。然后你只需要使用File方法。

那应该是这样的:

File sdCardRoot = Environment.getExternalStorageDirectory();
File yourDir = new File(sdCardRoot, "yourpath");
for (File f : yourDir.listFiles()) {
    if (f.isFile())
        String name = f.getName();
        // make something with the name
}

一点建议:来自 KitKat 及更高版本,这需要READ_EXTERNAL_STORAGE许可。

于 2010-12-30T08:53:22.407 回答
2
/**
 * Return list of files from path. <FileName, FilePath>
 *
 * @param path - The path to directory with images
 * @return Files name and path all files in a directory, that have ext = "jpeg", "jpg","png", "bmp", "gif"  
 */
private List<String> getListOfFiles(String path) {

    File files = new File(path);

    FileFilter filter = new FileFilter() {

        private final List<String> exts = Arrays.asList("jpeg", "jpg",
                "png", "bmp", "gif");

        @Override
        public boolean accept(File pathname) {
            String ext;
            String path = pathname.getPath();
            ext = path.substring(path.lastIndexOf(".") + 1);
            return exts.contains(ext);
        }
    };

    final File [] filesFound = files.listFiles(filter);
    List<String> list = new ArrayList<String>();
    if (filesFound != null && filesFound.length > 0) {
        for (File file : filesFound) {
           list.add(file.getName());
        }
    }

    return list;
}

这将为您提供文件夹中的图像列表。您可以修改代码以获取所有文件。

于 2010-12-30T08:53:30.977 回答
1

在 Android 5.0 Lollipop 中,我发现我们需要在 Manifest 中添加权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

如果没有,我们在 sdcard 中看不到任何文件。我需要一个小时才能找到这个!

于 2015-02-09T11:06:29.970 回答
0
 ArrayList<String>nameList = new ArrayList<String>();
 File yourDir = new File(Environment.getExternalStorageDirectory(), "/myFolder");
 for (File f : yourDir.listFiles()) 
 {
    if (f.isFile())
    {
       nameList.add(f.getName);
    }

}
于 2013-09-05T09:13:13.300 回答
0

如果您想从 FOLDER 的特定路径检索所有文件和文件夹,请使用此代码,它将帮助您

String path="/mnt/sdcard/dcim";  //lets its your path to a FOLDER

String root_sd = Environment.getExternalStorageDirectory().toString();
File file = new File(path) ;       
File list[] = file.listFiles();
  for(File f:list)
    {
       filename.add(f.getName());//add new files name in the list
     }              
于 2014-04-26T15:32:30.190 回答