我正在为程序添加一些功能,以便我可以通过读取MIME数据来准确地确定文件类型.我已经尝试过几种方法:
方法1:
javax.activation.FileDataSource
FileDataSource ds = new FileDataSource("~\\Downloads\\777135_new.xls");
String contentType = ds.getContentType();
System.out.println("The MIME type of the file is: " + contentType);
//output = The MIME type of the file is: application/octet-stream
Run Code Online (Sandbox Code Playgroud)
方法2:
import net.sf.jmimemagic.*;
try
{
RandomAccessFile f = new RandomAccessFile("~\\Downloads\\777135_new.xls", "r");
byte[] fileBytes = new byte[(int)f.length()];
f.read(fileBytes);
MagicMatch match = Magic.getMagicMatch(fileBytes);
System.out.println("The Mime type is: " + match.getMimeType());
}
catch(Exception e)
{
System.out.println(e);
}
//output = The Mime type is: application/msword
Run Code Online (Sandbox Code Playgroud)
方法3:
import eu.medsea.mimeutil.*;
MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector");
File f = …Run Code Online (Sandbox Code Playgroud)