Get filenames from a directory in Android

陌路散爱 提交于 2019-12-04 02:57:49

问题


I want to populate a spinner with the filenames of files found on the SD card with specific extensions. I can get it thus far to populate the spinner with the correct files, but the path is shown as well.

Can anyone tell me how to only get the filename of a specific file in a directory on the SD card?


回答1:


File sdCardRoot = Environment.getExternalStorageDirectory();
File yourDir = new File(sdCardRoot, "path");
for (File f : yourDir.listFiles()) {
    if (f.isFile())
        String name = f.getName();
        // Do your stuff
}

Have a look at Environment page for more info.




回答2:


Try below code

File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard, "yourpath");
for (File f : dir.listFiles()) {
    if (f.isFile())
        String name = f.getName();
        // do whatever you want with filename
}



回答3:


File filePath= new File(File Address);
File[] fileList = filePath.listFiles();
String name = fileList [0].getName().toString();



回答4:


could you process the string in reverse order(right to left), finding the first slash, then cutting the string at that point and taking the rightmost part of the string as the filename ?




回答5:


use method getName() of file object:

file.getName();



回答6:


Above answers are giving null pointer exception in my case. Following code worked for me:

File yourDir = new File(Environment.getExternalStorageDirectory().getPath() + "/WhatsApp/Databases");
    for (File f : yourDir.listFiles()) {
        if (f.isFile())
            name = f.getName();
        // Do your stuff
}


来源:https://stackoverflow.com/questions/8835693/get-filenames-from-a-directory-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!