How To Know The Filetype?
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 exte
Solution 1:
import java.net.FileNameMap;
import java.net.URLConnection;
publicclassFileUtils {
publicstatic String getMimeType(String fileUrl)throws java.io.IOException {
FileNameMapfileNameMap= URLConnection.getFileNameMap();
Stringtype= fileNameMap.getContentTypeFor(fileUrl);
return type;
}
publicstaticvoidmain(String args[])throws Exception {
System.out.println(FileUtils.getMimeType("file://c:/temp/test.TXT"));
// output : text/plain
}
}
Solution 2:
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()
.
Solution 3:
on Android, you can try something like this:
Filef= <YOUR FILE>
Stringpath= f.getAbsolutePath();
StringfileExtension=null;
intdotPos= path.lastIndexOf('.');
if (0 <= dotPos) {
fileExtension = path.substring(dotPos + 1);
}
if (!TextUtils.isEmpty(fileExtension )) {
Stringmime= MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension.toLowerCase());
if (!TextUtils.isEmpty(mime)) {
if (mime.startsWith("text")) {
// TEXT FILE
} elseif (mime.startsWith("image")) {
// IMAGE FILE
}
}
}
Solution 4:
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());
}
Solution 5:
The shortest way to find out file extension is using lastIndexOf('.')
assuming file name contains extension. Check the following code
StringfileName="test.jpg";
inti= fileName.lastIndexOf('.');
StringfileExtension= fileName.substring(i+1);
Log.v("FILE EXTENSION: ",fileExtension);
Post a Comment for "How To Know The Filetype?"