简体   繁体   中英

How to get complete path and name of each file in Download directory in Android

I am going to develop an app, where user can choose File from a Download directory. Now i need the path + name of the file, which the user has chosen.

DownloadManager dm = (DownlaodManager) getSystemService(DOWNLOAD_SERVICE);

By this way the user can choose the file. Now i need the absoloute path of the file, which is choosen. But the problem here is, if the user chosse a file, the file will be open(this shouldn't be happen)

Can anyone of you help me with that?

Use, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); to access the folder, and File.listFiles() to access individual files from that directory.

See this rough example,

write a method to browse and list each file from Downloads directory, and if a directory is found in Downloads folder, list its files too,

public void getFilesFromDir(File filesFromSD) {

    File listAllFiles[] = filesFromSD.listFiles();

    if (listAllFiles != null && listAllFiles.length > 0) {
        for (File currentFile : listAllFiles) {
            if (currentFile.isDirectory()) {
                getFilesFromDir(currentFile);
            } else {
                if (currentFile.getName().endsWith("")) {
                    // File absolute path
                    Log.e("File path", currentFile.getAbsolutePath());
                    // File Name
                    Log.e("File path", currentFile.getName());

                }
            }
        }
    }
}

Get the path of your Downloads directory and pass it as parameter in your above method,

File downloadDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOWNLOADS).getAbsolutePath());

getFilesFromDir(downloadDir);

Don't forget you'll need to set this permission in your manifest:

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

You can use WRITE_EXTERNAL_STORAGE instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM