Get File Extension And MIME Type In Android Development

This example shows how you can get file extensions and their MIME type in android.

Algorithm:

1.) Create a new project by File-> New -> Android Project name it GetFileExtensionWithMIMEType.

2.) Write following permissions into android manifest.xml:

 

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

 

3.) Run for output.

Steps:

1.) Create a project named GetFileExtensionWithMIMEType and set the information as stated in the image.

Build Target: Android 4.4
Application Name: GetFileExtensionWithMIMEType
Package Name: com.example. GetFileExtensionWithMIMEType
Activity Name: GetFileExtensionWithMIMEType

mime1

2.) Open GetFileExtensionWithMIMEType.java file and write following code there:

 

package com.example.getfileextensionwithmimetype;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class GetFileExtensionWithMIMEType extends ListActivity {

private List<String> fileList = new ArrayList<String>();

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

File root = new File(Environment
.getExternalStorageDirectory()
.getAbsolutePath());
ListDir(root);

}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
File selected = new File(fileList.get(position));
if(selected.isDirectory()){
ListDir(selected);
}else {
Uri selectedUri = Uri.fromFile(selected);
String fileExtension
= MimeTypeMap.getFileExtensionFromUrl(selectedUri.toString());
String mimeType
= MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);

Toast.makeText(GetFileExtensionWithMIMEType.this,
"FileExtension: " + fileExtension + "n" +
"MimeType: " + mimeType,
Toast.LENGTH_LONG).show();

}
}

void ListDir(File f){
File[] files = f.listFiles();
fileList.clear();
for (File file : files){
fileList.add(file.getPath());
}

ArrayAdapter<String> directoryList
= new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, fileList);
setListAdapter(directoryList);
}
}

 

3.) Compile and build the project.

Output

mime2

mime3