Get File Extension and MIME Type

We can call the methods getFileExtensionFromUrl() and getMimeTypeFromExtension() of android.webkit.MimeTypeMap class to get File Extension and MIME Type of a file.

example:

Get File Extension and MIME Type

package com.AndroidListFiles;

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

import android.app.ListActivity;
import android.content.Intent;
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 AndroidListFilesActivity 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(AndroidListFilesActivity.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);
}
}


Related Posts:
- List files/directory in Android
- Navigation in files/directory
- Start activity using intent of ACTION_VIEW, for specified MIME type.



0 Response to "Get File Extension and MIME Type"

Posting Komentar