2010-12-30 10 views

Respuesta

24

Environment.getExternalStorageDirectory le dará un File correspondiente a la SDCARD. Entonces solo tendrá que usar los métodos File.

Eso debería ser algo así:

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 
} 

Una pequeña nota de consejos: de KitKat y por encima, esto requiere el permiso READ_EXTERNAL_STORAGE.

+0

hey muchas gracias. – sajjoo

+0

¿Ha comprobado el código fuente de los dos métodos 'list()' y 'listFiles()'? Hay una pequeña diferencia entre ellos. Interesante saber cuál es la diferencia. –

+0

@Martjin: internamente, 'listFiles' usa la lista para crear una lista de nombres de archivos y crea objetos' File'. Pero como OP solo quería tener archivos, preferí usar 'listFiles'. –

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

Esto le dará la lista de imágenes en una carpeta. Puede modificar el código para obtener todos los archivos.

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

} 
0

Si desea recuperar todos los archivos y carpetas de una ruta específica de la carpeta a continuación, utilizar el código que le ayudará a

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

En Android 5.0 Lollipop, me encontré con que necesitamos agregar el permiso Manifiesto:

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

Si no, no pudimos ver ningún archivo en la tarjeta SD. ¡Tomo una hora para encontrar esto!

Cuestiones relacionadas