A_Javed
A_Javed

Reputation: 48

How to read file names of the files that are present in the android's Internal/External storage

I am trying to program my own file manager for android. What I want to know is that how can I read the file names of all the files present in external/internal storage? I want to read the file names and show them in a listview so the user could see what files are present in what folder. I know this thing is going to work in recursive manner as I have to read the content of sub directories as well.

Upvotes: 0

Views: 79

Answers (2)

Akshay Mukadam
Akshay Mukadam

Reputation: 2438

This is what you have to do. Before going to write please refer the File class in java. This will help you to clear lot of things. Below is the snippet that provides the list of files.

            File directory = new File(path);

            File[] listFiles = directory.listFiles();

            if (listFiles != null) {

                for (File file : listFiles) {
                    if (file.isDirectory())
                           // do the stuff what you need
                    else if (file.isFile()) {
                           // do the stuff what you need
                        }
                    }
                }
            }

Upvotes: 1

Anjali
Anjali

Reputation: 2535

Following code will give you list of files in android sdcard:

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

You can call same method to get sub directory file also.

Upvotes: 0

Related Questions