java.net.FileNameMap Interface in Java
Last Updated :
01 Dec, 2021
java.net.FileNameMap is a Java Interface. FileNameMap interface is a part of the java.net package. FileNameMap provides a mechanism to map between a file name and a MIME type string. We can use FileNameMap getContentTypeFor method to get the MIME type of the specified file.
Syntax:
public interface FileNameMap
Method of java.net.FileNameMap Interface
The FileNameMap Interface consists of only one method named as:
getContentTypeFor(String fileName) Method – It is a part of java.net.FileNameMap interface. As the method name suggests, getContentFor is used to get the MIME type in String format for a specific file.
Syntax:
String getContentTypeFor(String fileName)
Method Parameter: This method has only one parameter which is of String Type.
Method Return Type: It has a String return type and will return the MIME type for the file.
How to invoke getContentTypeFor method?
Step 1: It load fileNameMap from a data file using URLConnection.getFileNameMap() static method
FileNameMap fileNameMap = URLConnection.getFileNameMap();
Step 2: It invokes FileNameMap.getContentTypeFor(String fileName) method and pass on the fileName to get it’s MIME type
String mimeType = fileNameMap.getContentFor(String nameOfTheFile);
Example: Below is the java program for a better understanding of the FileNameMap interface and then to get the MIME type of the file using FileNameMap getContentTypeFor() method.
Java
import java.io.*;
import java.net.*;
class GFG {
public static void main(String[] args)
{
try {
FileNameMap fileNameMap
= URLConnection.getFileNameMap();
String firstFileName = "tmp.txt" ;
String secondFileName = "profile.png" ;
String thirdFileName = "gfg.mp4" ;
String firstFileMimeType = fileNameMap.getContentTypeFor(firstFileName);
String secondFileMimeType = fileNameMap.getContentTypeFor(secondFileName);
String thirdFileMimeType = fileNameMap.getContentTypeFor(thirdFileName);
System.out.println( "Mime type of "
+ firstFileName + " is "
+ firstFileMimeType);
System.out.println( "Mime type of "
+ secondFileName + " is "
+ secondFileMimeType);
System.out.println( "Mime type of "
+ thirdFileName + " is "
+ thirdFileMimeType);
}
catch (Exception e) {
System.out.println( "Some Exception "
+ e.getMessage());
}
}
}
|
Output
Mime type of tmp.txt is text/plain
Mime type of profile.png is image/png
Mime type of gfg.mp4 is video/mp4
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...