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
Bhavesh
source
to share
1 answer
Use
Files.probeContentType()
http://openjdk.java.net/projects/nio/javadoc/java/nio/file/Files.html#probeContentType(java.nio.file.Path)
And add custom detectors for any odd ball types you think you will come across.
Edit:
Here is the JavaDoc oracle for v7
http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#probeContentType(java.nio.file.Path)
+4
Java42
source
to share