简体   繁体   English

Android Studio listFiles返回资产文件夹为null

[英]Android Studio listFiles returns null with assets folder

In the assets folder I have another folder called songs with .txt files. 在资产文件夹中,我还有另一个文件夹,名为带有.txt文件的歌曲。 I've been trying to put all .txt files in a File[ ] but I get a NullPointer on folder.listFiles(). 我一直试图将所有.txt文件放入File [],但在folder.listFiles()上得到一个NullPointer。

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. 它们是设备上APK文件中的条目。

Use AssetManager to work with assets, including its list() method . 使用AssetManager处理资产,包括资产list()方法

As sir @CommonsWare mentioned, you can use AssetManager like this: 正如@CommonsWare先生所说,您可以像这样使用AssetManager:

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

Note that this file is String array. 请注意,此file是String数组。 So don't forget to initialize new file for each element of the array before iterating over it. 因此,不要忘记在遍历数组之前为数组的每个元素初始化新文件。

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

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