簡體   English   中英

如何在android中獲取存儲在sd卡中的文件名

[英]how to get the file names stored in sd card in android


我在SD卡中有一個包含多個文件的文件夾。 現在我需要獲取該文件的名稱。 任何人都知道如何獲取存儲在SD卡中的文件名?

任何幫助都將是值得的。 非常感謝。

Environment.getExternalStorageDirectory將為您提供與SDCARD相對應的File 然后你只需要使用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權限。

/**
 * 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;
}

這將為您提供文件夾中的圖像列表。 您可以修改代碼以獲取所有文件。

在Android 5.0 Lollipop中,我發現我們需要向Manifest添加權限:

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

如果沒有,我們在SD卡中看不到任何文件。 我需要一個小時才能找到這個!

 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);
    }

}

如果要從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
     }              

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM