简体   繁体   English

如何获取Android目录中的所有文件名?

[英]How to get all the filenames in android directory?

Im trying to list all the files in a particular folder of my android emulator and i keep getting null answer. 我试图列出我的Android模拟器的特定文件夹中的所有文件,而我一直得到空答案。

Heres my code: 这是我的代码:

File sdCardRoot = Environment.getExternalStorageDirectory();
File[] file= new File(sdCardRoot+"path");
for (File f : file.listFiles()) {
    if (f.isFile())
        String name = f.getName();

}

This doesnt seem to work dont know why. 这似乎不起作用,不知道为什么。

I've split the function in two parts, first function gets all the files in the given path and the second function gets the filenames from the file array. 我将函数分为两部分,第一个函数获取给定路径中的所有文件,第二个函数从文件数组中获取文件名。

public File[] GetFiles(String DirectoryPath) {
    File f = new File(DirectoryPath);
    f.mkdirs();
    File[] file = f.listFiles();
    return file;
}

public ArrayList<String> getFileNames(File[] file){
    ArrayList<String> arrayFiles = new ArrayList<String>();
     if (file.length == 0)
            return null;
        else {
            for (int i=0; i<file.length; i++) 
                arrayFiles.add(file[i].getName());
        }

    return arrayFiles;
}

change 更改

File[] file= new File(sdCardRoot+"path");

with

File[] file= new File(sdCardRoot, "path");

and make sure the directory path exits 并确保目录path退出

Just Check this: 只需检查一下:

  List<File> files = getListFiles(new File("YOUR ROOT")); 
  private List<File> getListFiles(File parentDir) {
      ArrayList<File> inFiles = new ArrayList<File>();
      File[] files = parentDir.listFiles();
      for (File file : files) {
          if (file.isDirectory()) {
          inFiles.addAll(getListFiles(file));
      } else {
          if(file.getName().endsWith(".csv")) {
              inFiles.add(file);
          }
      }
}

return inFiles;

Since sdCardRoot is instance of File , sdCardRoot+"path" will return the same thing as sdCardRoot.toString() + "path" . 由于sdCardRootFile实例,因此sdCardRoot+"path"将返回与sdCardRoot.toString() + "path"相同的东西。

However, calling file.toString() returns file name, but not absolute path. 但是,调用file.toString()返回文件名,但不返回绝对路径。 You need to call sdCardRoot.getAbsolutePath() + "path" . 您需要调用sdCardRoot.getAbsolutePath() + "path"

Also, make sure that you have allowed the emulator to use a certain amount of memory for external storage. 另外,请确保已允许仿真器将一定数量的内存用于外部存储。

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

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