简体   繁体   English

如何在Android的下载目录中获取每个文件的完整路径和名称

[英]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); 使用Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); to access the folder, and File.listFiles() to access individual files from that directory. 访问该文件夹,并使用File.listFiles()访问该目录中的单个文件。

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, 写入浏览并列出每个文件的方法Downloads目录,如果目录中找到Downloads文件夹中,也列出它的文件,

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, 获取Downloads目录的路径,并将其作为上述方法中的参数传递,

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. 您可以改用WRITE_EXTERNAL_STORAGE。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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