Android:从控制台中的目录中获取文件名

时间:2017-08-04 09:00:38

标签: java android file

我想从Android中的文件夹中listFiles(),但我得到了: java.lang.NullPointerException: Attempt to get length of null array

这是我尝试在控制台中打印的方式:

final File assetsFolder = new File("src/main/assets");
printFiles(assetsFolder);

private void printFiles(final File folder){
        for(final File fileEntry : folder.listFiles()){ //here is null
            if(fileEntry.isDirectory()){
                printFiles(fileEntry);
            } else {
                System.out.println(fileEntry.getName());
            }
        }
    }

这是我的项目结构:

Project
--ap
----src
------main
--------java
----------MainActivity <-- here I instantiate a class which is supposed to read files
--frameworkFolder
----src
------main
--------java <-- here is class with the code snippet I posted above
--------assets <- this is the folder which I want to read

我该如何处理错误?文件夹中实际存在文件。为什么编译器会说它为空?

1 个答案:

答案 0 :(得分:0)

尝试在资产文件夹中获取列表文件

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

或尝试更改

"src/main/asset"

"file:///android_asset/"