skip to Main Content

I am listing all the files in the "shared prefs" directory of an app. There are 3 shared prefs in total: "User.xml" and "Note_1.xml" and "Note_2.xml".

File f = new File("/data/data/com.bhiruva/shared_prefs/");
String[] pathnames;
pathnames = f.list();

That is the code I am using for listing all the files in that folder, but I need to list the files which only have the title starting as "note_"…

Can someone please tell me how to do this? Thanks in Advance

2

Answers


  1. You could do this:

    for(String pathname:pathnames){
        if(pathname.startsWith("Note_")){
            //do something
        }
    }
    
    Login or Signup to reply.
  2. Use a FilenameFilter to accept only the disired files:

    import java.io.File;
    import java.io.FilenameFilter;
    
    ....
    
    File f = new File("/data/data/com.bhiruva/shared_prefs/"); 
    
    String[] pathnames = f.list(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
           return name.toLowerCase().startsWith("note_");
        }
    });
    

    Or shorter using lambdas if you are using Java 8 or higher

    File f = new File("/data/data/com.bhiruva/shared_prefs/"); 
    
    String[] pathnames = f.list((dir, name) -> name.toLowerCase().startsWith("note_"));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search