Reputation: 240
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
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
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
Reputation: 69188
mime.types
files in your assets folder (for example from /etc/mime.types).activation.jar
(from JAF) in your build path.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();
}
Then use FileDataSource.getContentType()
to obtain file types.
Upvotes: 4