How to get the file extension in Android?

lots of ways . here are 2 sample-

String someFilepath = "image.fromyesterday.test.jpg"; 
String extension = someFilepath.substring(someFilepath.lastIndexOf("."));

So in you case, it should be something like that

String extension = ff.getAbsolutePath().substring(ff.getAbsolutePath().lastIndexOf("."));

In case if you don't want to do it yourself-

use FilenameUtils.getExtension from Apache Commons IO-

String extension = FilenameUtils.getExtension("/path/to/file/mytext.txt");

or in your case -

String extension = FilenameUtils.getExtension(ff.getAbsolutePath());

Kotlin Approach:

val fileExtention: String = file.extension

Check this: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/extension.html


You could just do it with one line of code using MIME Type Map.

First grab the file:

Uri file = Uri.fromFile(new File(filePath));

Then

String fileExt = MimeTypeMap.getFileExtensionFromUrl(file.toString());

You can put your code in your activity like this:

    private String getfileExtension(Uri uri)
        {
            String extension;
            ContentResolver contentResolver = getContentResolver();
            MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
            extension= mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri)); 
            return extension;
        }

"uri" is the file uri from the result of "Browse button" selected file