显示仅包含具有特定文件类型的文件的文件夹

时间:2015-03-05 15:23:06

标签: android

我已经设置了代码来显示SD卡上的所有文件夹,但现在我想知道如何只显示包含MP3文件的文件夹。

如何过滤掉不包含.MP3文件的文件夹?感谢。

类:

public class FragmentFolders extends ListFragment {
private File file;
private List<String> myList;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    myList = new ArrayList<String>();

    String root_sd = Environment.getExternalStorageDirectory().toString();
    file = new File(root_sd);

    File list[] = file.listFiles();

    for (int i = 0; i < list.length; i++) {
        myList.add(list[i].getName());
    }

    setListAdapter(new ArrayAdapter<String>(getActivity(),
            android.R.layout.simple_list_item_1, myList));

}

public void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

    File temp_file = new File(file, myList.get(position));

    if (!temp_file.isFile()) {
        file = new File(file, myList.get(position));
        File list[] = file.listFiles();

        myList.clear();

        for (int i = 0; i < list.length; i++) {
            myList.add(list[i].getName());
        }
        Toast.makeText(getActivity(), file.toString(), Toast.LENGTH_LONG)
                .show();
        setListAdapter(new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, myList));

    }

    return;
}

}

4 个答案:

答案 0 :(得分:1)

您可以使用fileNameFilter并过滤掉您不想要的文件夹/文件。

File baseDirectory = new File("/mnt/sdcard/"); //Your base dir here
File[] files = baseDirectory.listFiles(new FilenameFilter() {
    @Override
    public boolean accept(File dir, String fileName) {
    File possibleMp3Folder = new File(dir, fileName);
    if (possibleMp3Folder.isDirectory()) {
        File[] files1 = possibleMp3Folder.listFiles();
        for (File file : files1) {
            if (file.getName().toLowerCase().endsWith(".mp3")) {
                return true;
            }
        }
   }

   return false;
}
});

答案 1 :(得分:1)

在添加到列表视图的数据集之前,您可以检查目录中的文件是否是mp3文件

修改您的代码,如下所示:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

     myList = new ArrayList<String>();

        String root_sd = Environment.getExternalStorageDirectory().toString();
        file = new File(root_sd);

        //list content of root sd

        File list[] = file.listFiles();

        for (int i = 0; i < list.length; i++) {

                //check the contents of each folder before adding to list

                File  mFile = new File(file, list[i].getName());
                File dirList[] = mFile.listFiles();
                   if(dirList == null) continue;
                  for (int j = 0; j < dirList.length; j++) {
                    if(dirList[j].getName().toLowerCase(Locale.getDefault()).endsWith(".mp3")){
                    myList.add(list[i].getName());
                    break;
                    }
              }

        }

        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, myList));
}

我测试了这个并且它有效。唯一需要注意的是,它不会检查子目录。

所以:

sdcard/Music/mistletoe.mp3
sdcard/Media/Tracks/mistletoe.mp3

仅列出音乐文件夹。

此外,您可能希望使用asyncTask来避免占用UI线程

答案 2 :(得分:0)

如果您要查找包含 mp3 文件的所有文件夹(均在内部存储和SD卡上),并且可用存储包含媒体

  1. 媒体存储路径 mp3文件夹路径初始化两个集:

    private HashSet<String> storageSet = new HashSet<>();
    private HashSet<String> folderSet = new HashSet<>();
    
  2. 在一个方法中获取两者(如果只需要一个方法,则可以返回值):

    private void getMediaFolders() {
        ContentResolver resolver = getContentResolver();
    
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
        String[] projection = { MediaStore.Audio.Media.DATA };
    
        Cursor cursor = resolver.query(uri, projection, selection, null, null);
    
        if(cursor != null && cursor.getCount() > 0) {
            int dataIndex = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
    
            while(cursor.moveToNext()) {
                String data = cursor.getString(dataIndex);
    
                int i = 0;
                for (int slashCount = 0; i < data.length(); i++) {
                    if (data.charAt(i) == '/' && ++slashCount == 3) {
                        storageSet.add(data.substring(0, i));
                        break;
                    }
                }
    
                if (data.toLowerCase().endsWith("mp3")) {
                    int lastSlashIndex = data.lastIndexOf('/');
                    while (i < lastSlashIndex) {
                        data = data.substring(0, lastSlashIndex);
                        folderSet.add(data);
                        lastSlashIndex = data.lastIndexOf('/');
                    }
                }
            }
        }
    
        if (cursor != null) { cursor.close(); }
    }
    
  3. 过滤文件夹(使用Annimonstream):

    private ArrayList<File> getFilteredFolders(@NonNull String path, HashSet<String> folderSet) {
        File[] filesList = new File(path).listFiles();
    
        if (filesList == null) { return new ArrayList<>(); } // Or handle error as you wish
    
        return Stream.of(filesList)
            .filter(File::isDirectory)
            .filter(f -> folderSet.contains(f.getAbsolutePath()))
            .collect(Collectors.toCollection(ArrayList::new));
    }
    
  4. 显示存储空间(如果需要)。

答案 3 :(得分:0)

               Uri,Projection,
                            MediaStore.Video.Media.DATA
                            + " like " + "'%.mp4%'"
                            + " AND "
                            + MediaStore.Video.Media.DATA
                            + " like " + "'%" + getResources().
                            getString(R.string.string_store_video_folder) 
                            +"%'", null,
                    MediaStore.Video.Media.DATE_MODIFIED

这将在特定文件夹中提供mp4文件