FileNameMap fileNameMap = URLConnection.getFileNameMap(); String type = fileNameMap.getContentTypeFor(fileUrl); return type; } public static void main(String args[]) throws Exception { System.out.println(FileUtils.getMimeType("file://c:/temp/test.TXT")); // output : text/plain } }...
Magicparser=newMagic() ;MagicMatchmatch=parser.getMagicMatch(newFile("E:\\static\\count.mp3")); System.out.println(match.getMimeType()) ; 4、java.net.* Tips:貌似mp3音频文件获取为null,这种暂时不推荐 importjava.net.FileNameMap;importjava.net.URLConnection;publicclassTest{publicstaticvoidmain(St...
publicvoidtest(){File file =newFile("d:/test.png"); URLConnection connection = file.toURL().openConnection(); String mimeType = connection.getContentType();} 结果:结论:根据文件流中前几个字符判断。能够判断真实的文件类型,但是,这种方法的主要缺点是速度非常慢。2.2 使用guessContentType...
public void whenUsingGetFileNameMap_thenSuccess(){ File file = new File("product.png"); FileNameMap fileNameMap = URLConnection.getFileNameMap(); String mimeType = fileNameMap.getContentTypeFor(file.getName()); assertEquals(mimeType, "image/png"); } 1. 2. 3. 4. 5. 6. 7. 8. ...
How do you get a Media Type (MIME type) from a file using Java? So far I've tried JMimeMagic & Mime-Util. The first gave me memory exceptions, the second doesn't close its streams properly. How would you probe the file to determine its actual type (not merely based on the extensi...
import java.io.File; class GetMimeType { public static void main(String args[]) { File f = new File("gumby.gif"); System.out.println("Mime Type of " + f.getName() + " is " + new MimetypesFileTypeMap().getContentType(f)); ...
最有趣的类是javax.activation.MimeType-一个实际的MIME型保持架-和javax.activation.MimetypesFileTypeMap-类,其实例可以将MIME类型解析为文件的字符串:String fileName = "/path/to/file";MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();// only by file nameString mimeType = mimeTypesMap.get...
mimeType= URLConnection.guessContentTypeFromName(file.getName()); 还有以下内容,它的优点不仅仅是使用文件扩展名,还可以查看内容。 InputStream is = new BufferedInputStream(new FileInputStream(file));mimeType = URLConnection.guessContentTypeFromStream(is); //...close stream 然而,正如上面的注释所建议的...
String type =null; URL u =newURL(fileUrl); URLConnection uc =null; uc = u.openConnection(); type = uc.getContentType(); returntype; } publicstaticvoidmain(String args[])throwsException { System.out.println(FileUtils.getMimeType("file://c:/temp/test.TXT")); ...
以下是一个使用Java代码获取文件MIME类型的示例: importjava.io.File;importjava.io.IOException;importjava.net.URLConnection;publicclassFileMimeTypeExample{publicstaticvoidmain(String[]args){Filefile=newFile("example.txt");try{StringmimeType=getMimeType(file);System.out.println("File MIME type: "+mime...