android 如何读取设备中的所有文件和目录?

8yoxcaq7  于 2022-12-31  发布在  Android
关注(0)|答案(1)|浏览(183)

有没有可能开发一个Java应用程序,可以读取设备内存中的所有文件和目录?
我认为这是不可能的(出于安全考虑),但我需要另一种意见。

0dxa2lsx

0dxa2lsx1#

你可以这样做。
我将采取 * 路径 * 是设备存储。
如果您使用的是Android Studio或类似的工具,请将调试点放在:

File[] dir = new File(path).listFiles();

您将看到文件/文件夹层次结构。

path = Environment.getExternalStorageDirectory().toString()

public static ArrayList<String> listFoldersAndFilesFromSDCard(String path) {
    ArrayList<String> arrayListFolders = new ArrayList<String>();

    try {
        File[] dir = new File(path).listFiles();
        // Here 'dir' will give you a list of folder/files in the hierarchy

        if (null != dir && dir.length > 0) {
            for (int i = 0; i < dir.length; i++) {
                if (dir[i].isDirectory()) {
                    arrayListFolders.add(new File(dir[i].toString()).getName());
                    // Here you can call recursively this
                    // function for file/folder hierarchy
                }
                else {
                    // Do whatever you want with the files
                }
            }
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return arrayListFolders;
}

相关问题