10

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?

CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
user1145581
  • 1,017
  • 4
  • 13
  • 18

6 Answers6

27
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.

Siva Charan
  • 17,940
  • 9
  • 60
  • 95
3

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
}
Yugandhar Babu
  • 10,311
  • 9
  • 42
  • 67
2
File filePath= new File(File Address);
File[] fileList = filePath.listFiles();
String name = fileList [0].getName().toString();
rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
Kazem Maleki
  • 179
  • 3
  • 6
0

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
}
0

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 ?

alshapton
  • 568
  • 5
  • 17
0

use method getName() of file object:

file.getName();
waqaslam
  • 67,549
  • 16
  • 165
  • 178