fixxer
fixxer

Reputation: 240

How to determine file types in Android

What is the best way to determine a file type in Android?

I want to check if the given file is an image, a music file, etc.

Upvotes: 4

Views: 4667

Answers (3)

Cytown
Cytown

Reputation: 1547

A common way is by their extension only, or you can parse the header, but it should be too much slower and more complex for your apps.

Upvotes: 1

Nizzy
Nizzy

Reputation: 1889

public static String getMimeType(String fileUrl) {
    String extension = MimeTypeMap.getFileExtensionFromUrl(fileUrl);
    final String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    return (mimeType !=  null) ? mimeType : "unknown";
}

Upvotes: 1

Diego Torres Milano
Diego Torres Milano

Reputation: 69188

  1. Include some mime.types files in your assets folder (for example from /etc/mime.types).
  2. Include activation.jar (from JAF) in your build path.
  3. Use something like this:

    try {
        MimetypesFileTypeMap mftm = 
            new MimetypesFileTypeMap(getAssets().open("mime.types"));
        FileTypeMap.setDefaultFileTypeMap(mftm);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
  4. Then use FileDataSource.getContentType() to obtain file types.

Upvotes: 4

Related Questions