What is the best approach to define a specific file type in Java?
I am trying to use the following approach to identify specific file types using Java. I need to implement things like this 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 to the console.
image/jpeg
text/plain
application/zip
null
null
null
null
In the last four cases, it displays null
and cannot recognize the file type of this file. What is the best approach for detecting a specific file type in Java?
+3
source to share