简体   繁体   中英

Android Studio listFiles returns null with assets folder

In the assets folder I have another folder called songs with .txt files. I've been trying to put all .txt files in a File[ ] but I get a NullPointer on folder.listFiles().

Here's the code :

    File folder = new File("assets/songs");
    File[] listOfFiles = folder.listFiles();


    for (int i = 0; i < listOfFiles.length; i++) {
        File file = listOfFiles[i];
        if (file.isFile() && file.getName().endsWith(".txt")) {
            String content = FileUtils.readFileToString(file);
            this.list.add(content);
            System.out.println(content);
        }
    }

    return this.list;

Assets are not files on the device. They are files on the development machine. They are entries inside the APK file on the device.

Use AssetManager to work with assets, including its list() method .

As sir @CommonsWare mentioned, you can use AssetManager like this:

AssetManager assetManager = getAssets();
String[] files = assetManager.list("");

Note that this file is String array. So don't forget to initialize new file for each element of the array before iterating over it.

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