2016-09-15 43 views
0

我有读取每个文件夹并尝试读取移动设备中的mp3文件的代码。但问题在于,它会针对设备中的每个子文件夹及其拥抱时间。我想要的是。我想限制我的搜索条件,直到5个子文件夹。平均文件夹和直到3个子文件夹。像
/存储/ sdcard0/
/存储/ sdcard0 /安卓/
/存储/ sdcard0 /安卓/数据/只读android文件夹直到5个子文件夹

这个文件夹就需要检查下一个文件夹后。即 /Storage/sdcard0/download

这里是我的代码。

int folderno = 0; 

public ArrayList<HashMap<String, String>> getPlayList(String rootPath) { 
    ArrayList<HashMap<String, String>> fileList = new ArrayList<>(); 


    try { 
     File rootFolder = new File(rootPath); 
     File[] files = rootFolder.listFiles(); //here you will get NPE if directory doesn't contains any file,handle it like this. 
     for (File file : files) { 
      if (folderno <3 && file.isDirectory()) { 
       folderno = folderno + 1; 

       if (getPlayList(file.getAbsolutePath()) != null) { 

        fileList.addAll(getPlayList(file.getAbsolutePath())); 
       } else { 
        folderno = 0; 
        //break; 
       } 
      } else if (file.getName().endsWith(".mp3")) { 



       // folderno = folderno - 1; 
       HashMap<String, String> song = new HashMap<>(); 
       song.put("file_path", file.getAbsolutePath()); 
       song.put("file_name", file.getName()); 
       fileList.add(song); 
      } 
     } 
     folderno = 0; 
     return fileList; 
    } catch (Exception e) { 

     return null; 
    } 
} 

我试图包括一些逻辑,但它现在的工作。我创建了folderno作为变量并检查它。 预先感谢您....

回答

0

我在Eclipse中尝试这个

private int count = 0; 
private void readFiveDir(File file) { 
    count++; 
    System.out.println("Directory/File Name : " + file.getName()); 
    System.out.println("Folder No : " + count); 
    if(file.isDirectory()) { 
     if(count == 5) { 
      return; 
     } 
     for(File currFile : file.listFiles()) { 
      readFiveDir(currFile); 
     } 
    } 
} 

我的目录结构:

Directory Structure

 
Output : 

Directory/File Name : Dir1 
Folder No : 1 
Directory/File Name : Dir2 
Folder No : 2 
Directory/File Name : Dir3 
Folder No : 3 
Directory/File Name : Dir4 
Folder No : 4 
Directory/File Name : Dir5 
Folder No : 5 
Directory/File Name : Dir5a 
Folder No : 6 
Directory/File Name : Dir5a_1 
Folder No : 7 
Directory/File Name : Dir5a_2 
Folder No : 8 
Directory/File Name : Dir5b 
Folder No : 9 
Directory/File Name : Dir5b_1 
Folder No : 10 
Directory/File Name : Dir5b_2 
Folder No : 11 
Directory/File Name : Dir2a 
Folder No : 12 
Directory/File Name : Dir2b 
Folder No : 13 

试试吧,让我知道。

相关问题