Question

I want to know whether the file is Audio(mp3,aac, etc), Video(mp4,wmv,3gp,etc), Document(txt,rtf,doc,docx,xls,xlsx,ppt,html etc) or Unknown (with no extension and other custom extension specific for one single application in the near future)

I need to implement it in Android. I think I could find the extension of file and identifying its type? Or do I not need to know the extension?

I just want to know the file-type.

Was it helpful?

Solution

You can either try to guess the file type from the filename extension using guessContentTypeFromName(), or you can try to guess the file type from the content using guessContentTypeFromStream().

OTHER TIPS

import java.net.FileNameMap;
import java.net.URLConnection;

public class FileUtils {

public static String getMimeType(String fileUrl)
  throws java.io.IOException {
      FileNameMap fileNameMap = URLConnection.getFileNameMap();
      String type = fileNameMap.getContentTypeFor(fileUrl);

     return type;
}

public static void main(String args[]) throws Exception {
      System.out.println(FileUtils.getMimeType("file://c:/temp/test.TXT"));
     // output :  text/plain
   }
}

http://www.rgagnon.com/javadetails/java-0487.html

on Android, you can try something like this:

File f = <YOUR FILE>

String path = f.getAbsolutePath();
String fileExtension = null;
int dotPos = path.lastIndexOf('.');
if (0 <= dotPos) {
    fileExtension = path.substring(dotPos + 1);
}

if (!TextUtils.isEmpty(fileExtension )) {
    String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension.toLowerCase());
    if (!TextUtils.isEmpty(mime)) {
        if (mime.startsWith("text")) {
        // TEXT FILE
        } else if (mime.startsWith("image")) {
        // IMAGE FILE
        }
    }
}

You can use mime-util library. My sample code will get the mime type of the file.

    String imagePath = "/tmp/test.txt";
    File file = new File(imagePath);

    if (MimeUtil.getMimeDetector(MagicMimeMimeDetector.class.getName()) == null)  {
        MimeUtil.registerMimeDetector(MagicMimeMimeDetector.class.getName());
    }
    Collection<MimeType> mimeTypes = MimeUtil.getMimeTypes(file);
    for (MimeType mimeType : mimeTypes) {
        System.out.println(mimeType.getMediaType());
    }

The shortest way to find out file extension is using lastIndexOf('.') assuming file name contains extension. Check the following code

String fileName = "test.jpg";
int i = fileName.lastIndexOf('.');
String fileExtension = fileName.substring(i+1);
Log.v("FILE EXTENSION: ",fileExtension);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top