I'm trying to use the following approach to identify specific file types using Java. I need to implement such things in my web application.
package filetype;
import java.io.File;
import java.net.URLConnection;
final public class FileType
{
public static void main(String[] args)
{
File temp=new File("G:/mountain.jpg");
System.out.println(URLConnection.guessContentTypeFromName(temp.getAbsolutePath()));
temp=new File("G:/myFile.txt");
System.out.println(URLConnection.guessContentTypeFromName(temp.getAbsolutePath()));
temp=new File("G:/zipByJava.zip");
System.out.println(URLConnection.guessContentTypeFromName(temp.getAbsolutePath()));
temp=new File("G:/MLM/Login.aspx");
System.out.println(URLConnection.guessContentTypeFromName(temp.getAbsolutePath()));
temp=new File("G:/power_point.pptx");
System.out.println(URLConnection.guessContentTypeFromName(temp.getAbsolutePath()));
temp=new File("G:/excel_sheet.xlsx");
System.out.println(URLConnection.guessContentTypeFromName(temp.getAbsolutePath()));
temp=new File("G:/word_document.docx");
System.out.println(URLConnection.guessContentTypeFromName(temp.getAbsolutePath()));
}
}
It displays the following output on the console.
image/jpeg
text/plain
application/zip
null
null
null
null
In the last four cases, it displays null
and fails to recognize the file type of a given file. What is the best approach to identify a specific file type in Java?