Pecurka
Pecurka

Reputation: 113

How to find files in a folder that name starts with a specific String in Android

Can someone help me...

I am making an Android app and i need now to search for files in Download folder of my device and if i find files that name starts with data then call a function.

Thanks.

Upvotes: 3

Views: 5485

Answers (3)

earthw0rmjim
earthw0rmjim

Reputation: 19417

Something like this should work:

File dir = Environment
    .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File[] files = dir.listFiles();

for (File file : files) {
    if (file.getName().startsWith("data")) {
        // it's a match, call your function
    }
}

Don't forget to add the READ_EXTERNAL_STORAGE permission to your manifest:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Since the protectionLevel of this permission is dangerous, on API level 23+ you need to request this permission at runtime. Check out the corresponding developer's guide article.

Upvotes: 5

Navneet kumar
Navneet kumar

Reputation: 1964

   ArrayList< File > getFileList( File downloadFolder, String preFixFilter )
   {
       ArrayList< File > filteredFileList = new ArrayList< File >();
       for( File file : downloadFolder.listFiles() )
       {
            if( file.getName().toLowerCase().startsWith( preFixFilter.toLowerCase() ) )
            {
                 filteredFileList.add( file );
            }
       }
       return filteredFileList;
   }

Upvotes: 0

Manish Kumar
Manish Kumar

Reputation: 589

You should do the following changes to your code :-

1) Add android.permission.WRITE_EXTERNAL_STORAGE to your manifest.xml file

2) Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); Then you can use File.list() or File.listFiles() to get all the file in the directory into array .

You can loop on the returned array and you can use regular expression to search the file :-

Pattern pattern = Pattern.compile("^data");

Then write the matcher statement :-

Matcher matcher = pattern.matcher(file.getName());               
 if(!matcher.find()) {
            // do your method call here                     
 }

Hope it helps you.

Upvotes: 0

Related Questions